Menu
  • HOME
  • TAGS

valgrind error Invalid read of size 8

c,memory-leaks,malloc,valgrind

You need to test before you use. while (party->members[i] != NULL && i < party->maxMembersNum) should be while (i < party->maxMembersNum && party->members[i] != NULL) ...

Allocating space for upper triangular matrices in algebraic notation

c,matrix,malloc,free,algebra

There's a problem on this line: m--; for(i = 0; i < n; i++) { m[i]--; } You're decrementing m, but then go ahead and index it from 0 ... I guess you may end up messing up the heap structures. I managed to have your code valgrind error-free like...

How to allocate memory to struct pointer using malloc.h header?

c,pointers,struct,malloc,dynamic-memory-allocation

This worked (on C and C++). Since you originally included both tags. change *c =(struct student)malloc(sizeof(struct student)); to c =(struct student*) malloc(sizeof(struct student)); ...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

C dynamic allocation of a 2D array in a function & return pointer

c,arrays,malloc

You need to pass a pointer to your int **array; pointer. func will therefore take an int ***arrayp argument. Modify the code this way: void func(int rows, int ***arrayp); int main() { int **array; int rows = 2; func(rows, &array); // do some stuff with info from array[rows][2] free(array); }...

Deallocating 2D array in C

c,arrays,malloc,free

You allocate space for s doubles for each block_mat[i]. Later, you access block_mat[i][block_index] = 0; block_index++; but you never check that block_index goes out of bounds, which it does. If you write beyond the s allocated doubles, you might corrupt the internal control data for the subsequent pointer, which usually...

Random double free or invalid next_size

c,malloc,size,free

In sup_read(), you have: uint8_t *rx_buff = (uint8_t *) malloc(1500); int exit = 1; int length = 0; while (exit) { length = recvfrom(s, rx_buff, 65535, 0, NULL, NULL); You allocate 1500 bytes, but you tell recvfrom() that it has 65535 bytes to play with. That could be a part...

How can I change maximum available heap size for a task in FreeRTOS

embedded,malloc,heap,keil,freertos

(Yes - FreeRTOS pvPortMalloc() returns void*.) If you have 60K of SRAM, and configTOTAL_HEAP_SIZE is large, then it is unlikely you are going to run out of heap after allocating 256 bytes unless you had hardly any heap remaining before hand. Many FreeRTOS demos will just keep creating objects until...

How will you free the memory allocated?

c,memory-management,malloc,free,dynamic-memory-allocation

It's simple. You can use this code to clean your only used variable. #include<stdio.h> #include<stdlib.h> #define MAXROW 3 #define MAXCOL 4 int main() { int **p, i, j; p = (int **) malloc(MAXROW * sizeof(int*)); free(p); return 0; } ...

How I can add an adjacency list to a node of defined type in C?

c,struct,malloc

(borrowing) I think this will work for you... typedef struct _node { int data; int neighboursNumber; struct _node **neighbours; } node; int main( void ) { node *n1 = (node *)malloc(sizeof(node)); n1->data = 1; n1->neighboursNumber = 2; n1->neighbours = (node **)malloc(sizeof(node *) * n1->neighboursNumber); node * n2 = (node *)malloc(sizeof(node));...

malloc doesn't allocate 3d array properly

c,arrays,pointers,compiler-errors,malloc

You can't write sizeof(*int) you have to write sizeof(int*). Also, see this answer to see how to better create your array...

HeapValidate Fails

c,pointers,malloc,free

Your code for inserting an element looks suspect: temp = (struct elements*) malloc(sizeof(struct elements*)); ...fill the values... I think you want sizeof(struct elements), not the size of the pointer: temp = (struct elements*) malloc(sizeof(struct elements)); ...fill the values... ...

Not sure how to use malloc() and free() properly

c,pointers,memory-management,malloc,free

You cannot use the memory once you free() it. So, free(len); return *len; is wrong and undefined behavior. Instead, you can use a local variable to hold the value and return it. Also, FWIW, int *len = (int *)malloc(sizeof(int)); if(!r) { free(len); return *len; } in the above code, you're...

is this code correct?If yes then malloc is already assigning the addresses to name[i] variable then why strcpy is used?

c,string,pointers,malloc,strcpy

Line 5 merely allocates space. The memory allocated by malloc() has unspecified values.

c++ unsigned char array allocation - segmentation fault

c,segmentation-fault,malloc,memset,unsigned-char

It seems that your program is written in C instead of C++. In C++ you should use operator new [] instead of malloc. The problem with the function is that function parameters are its local variables. So the function parameter char *data is a copy of its argument declared in...

Changing the pointer inside a function does not reflect outside the function [duplicate]

c,pointers,malloc,pass-by-reference,pass-by-value

You need this: void alloco(int **ppa) { int i; printf("inside alloco %p\n",ppa); *ppa = malloc(20 * sizeof(int)); (*ppa)[15] = 9; // rather pointless, in the loop below (*ppa)[15] will be // overwritten anyway printf("size of a %d \n", sizeof(*ppa)); // rather pointless, not sure // what you want to print...

Is setting environment variable through a makefile - possible?

c,unix,makefile,malloc,gnu-make

Browning, setting an environment variable in the makefile is easy, and you have done so, but that is not what you want. That makes it take that value during the compile. But you want it to change malloc's behavior when you run the program. Reading the man page you referenced...

Initially mallocate 0 elements to later reallocate and measure size

c,arrays,malloc,realloc

You could initialize your pointer to NULL, so that the first time you call realloc(yourPointer, yourSize), it will return the same value as malloc(yourSize). For your second problem, you could use a struct that contains your pointer and a count member. struct MyIntVector { int * ptr; size_t count; }...

How to use munmap custom malloc

c++,c,malloc,mmap

You are unmapping the entire page. The address addr must be a multiple of the page size. All pages containing a part of the indicated range are unmapped, and subsequent references to these pages will generate SIGSEGV. It is not an error if the indicated range does not contain any...

malloc and free in linux aborted [closed]

c,linux,malloc,free

You problem is probably caused by bugs in your code. Memory bugs (buffer overruns, using memory after it has been freed, freeing the same memory twice, etc) can be hard to locate. Run it with Valgrind. Valgrind is a tool that will help you find bugs related to malloc()/free(). Edit:...

__free_hook doesn't hook as expected

c,malloc

_free_initialize_hook Is never called. You need to remove static void init_free_hooks(void) { old_free_hook = __free_hook; __free_hook = new_free_hook; } void (*volatile __free_initialize_hook)(void) = init_free_hooks; And init both hooks in your init_malloc_hooks: static void init_malloc_hooks(void) { old_malloc_hook = __malloc_hook; __malloc_hook = new_malloc_hook; old_free_hook = __free_hook; __free_hook = new_free_hook; } ...

17653 Segmentation fault (core dumped)

pointers,malloc,openmp,double-pointer

void matrix_vector_gen(int size, double **matrix, double **matrix2){ int i,j; for(i=0; i<size; i++) for(j=0; j<size*size; j++) matrix[i][j] = ((double)rand())/5307.0; matrix2[i][j] = ((double)rand())/65535.0; } when you leave braces out only the next statement after the "for" statement is executed in the loop, so the "matrix2" line is executed after the loops end,...

malloc and realloc size of integer array

c,arrays,malloc

You could also first reserve a specific amount of memory i.e: If the user inputs more than 10 items you realloc another block of memory of say 20 integers and copy the last 10 items into the new block and so on. size_t block_length = 10; size_t current_length = 0;...

Why is _stprintf_s overwriting other variables but _stprintf is not?

c++,winapi,printf,malloc

also in my runs semaphores are overwritten with value 0xfefefefe This is a "magic value", it is written by the safe CRT functions (like _stprintf_s) to help you debug mistakes in the buffer length you pass. The debug build of these functions fill the entire buffer, using 0xfe as...

Free list implementation not working properly

c,malloc,free

As WhozCraig diagnosed, the problem is more that the code does not stop when it gets to the end of the free list because it is a circular list and the termination condition is looking for null pointers that don't exist. You can fix most of the problems by rewriting...

Does C have a shorthand way of initialize a struct with malloc and set its fields?

c,data-structures,struct,initialization,malloc

You can write your own wrapper function: static node *getNewNode(char *fx) { node *p = calloc(1, sizeof *p); if(p && fx) { p->fx = malloc(strlen(fx) + 1); if(!p->fx) { free(p); p = null; } else { strcpy(p->fx, fx); } } return p; } Later you can call this as: node...

Segmentation fault when trying to allocate memory for a string via a pointer-to-pointer function call

c,pointers,file-io,segmentation-fault,malloc

In your readFileToBuffer() code, fileBuffer is of type char ** and your function is called as readFileToBuffer("/tmp/file.txt", &fileBuffer); Then you have rightly allocated memory to *fileBuffer in readFileToBuffer() [so that is gets reflected to the fileBuffer in main()]. So, you need to pass *fileBuffer to fread() to read the contents...

How to initialize a 3d array in C - Array of arrays of pointers

c,arrays,pointers,malloc

you should not have a function in a function, move InitBranches out of generatePossibleMoves. Also the typedef struct should be outside of the function. Your declaration of array and the malloc do not match, you should remove a * in the declaration or add one in the sizeof. just a...

Cannot free fileName char * after fclose

c,memory-management,malloc,free,realloc

You code is having issue in the below line strcat(*indexFileName, ".ind") the destination buffer at *indexFileName is having insufficient memory to hold the concatenated string. Hence it invokes undefined behaviour. From the man page of strcat() ... If dest (destination buffer) is not large enough, program behaviour is unpredictable; So,...

Allocating std vector content with dynamic objects

c++,malloc,std,stdvector

You can just reserve enough space in vector, so it will allocate memory only once. Also it is a good practice to use std::unique_ptr<>: std::vector<std::unqiue_ptr<MyObject> > my_vector; int object_count = 10000; my_vector.reserve(object_count); for(int index = 0; index < object_count; index++) { my_vector.push_back(std::unique_ptr<MyObject>(new MyObject())); } Update: if you can not use...

Dynamically creating a 2D array of pointers using malloc in C

c,arrays,pointers,malloc

First of all, please think twice about the program design. Do you really need a 2D array of pointers, each pointing to a struct, each struct containing a number of items? Those requirements are rather complex: if you can simplify them, your program will turn out much better. Because with...

C - Why is a fixed size array performing much slower than a dynamically allocated array?

c,arrays,malloc

I'm surprised it would make this much of a difference, but since you realloc() the rates array for each line of data read, it's likely that the cost of copying that array so often is the culprit. If the target is a 32-bit machine, the Rates_t structure that contains the...

c - getting a heap error when trying to free

c,pointers,malloc,free,strcat

As per the man page of strcat(), char *strcat(char *dest, const char *src); [..] and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable; In your string_utils_part_of_string() function, you did not allocate enough memory to the result to be...

size of a node in linked list

c++,malloc,sizeof

head is not a node, it is a pointer to a node. So sizeof(head) gives you the size of a pointer, which has no relation to the size of the thing it points at. sizeof(*head) would give you the size of a node.

Call to malloc() causes unexplicable program crash

c,string,segmentation-fault,malloc,dynamic-memory-allocation

Point 1 for (i = 0; input[i] != ','; i++){ is unsafe. if your input does not contain , you'll be overrunning memory. Instead use something like int len = strlen(input); for (i = 0; (input[i] != ',') && len ; i++, len--){ Point 2 in C, we have 0...

Freeing array of dynamic strings / lines in C

c,string,sorting,malloc,free

There are multiple problems in your code: function getline: the string in the line buffer is not properly '\0' terminated at the end of the do / while loop. It does not free the line buffer upon end of file, hence memory leak. It does not return a partial line...

free causing different results from malloc

c,string,malloc,free

Every time you are creating your string, you are not appending a null terminator, which causes the error. So change this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; } } to this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; }...

pointed data in function with malloc keeps disappearing outside of it

c,pointers,malloc

These lines: if(root==NULL) { root=newnode; return 1; } modify root in the function but don't change the value of the same variable in the calling function. The value of root in the calling function continues to be NULL and you leak every node allocated by the call to malloc. One...

How can I deallocate my memory? [duplicate]

c,malloc,free

You only need to use free(pointer to your allocated memory ), so in your case: free(new_str); Use it at the end, when you're using anymore this memory. For example: } //Here } else { ...

Difficulties with understanding reallocating using malloc

c,memory-leaks,malloc,runtime-error

You free the final value of collection.words, which is a pointer to the end of original memory block (due to ++ in a loop). void increaseCollectionSize(){ collection.size = (collection.size + 1) * REALLOCATE_MODIFIER; char **increasedCollection = malloc(sizeof(char *) * collection.size); char **increasedHead = increasedCollection; char **originalWords = collection.words; // save...

Accessing char array inside struct showing out of bounds error

c,arrays,struct,malloc,dynamic-memory-allocation

Array index in C is 0 based. For an array with 50 bytes of memory allocated, char name[50]; trying to use [50] as index is off-by-one and invokes undefined behaviour. That said, newPerson->name[50] = *nameInputPtr; is not the way you copy a string. You need to make use of strcpy(),...

C - strcpy with malloc size less than argument's size [duplicate]

c,malloc,strcpy

It's called undefined behavior, since it's undefined sometimes it works. Yes you can write past a memory block in c, but that's illegal because it invokes undefined behavior, the behavior is therefore not predictable and your program might or might not work. What you expect from strcpy() doesn't happen because...

Passing pointers to functions with and without &

c,pointers,malloc

The rule is really very simple. You want to call a function that takes a pointer to a struct object. If you already have a pointer to the object you want to use that function on, you don't need &. Otherwise, you do. What do I mean by "already have...

function to get 2d-arrays from stack and heap

c,arrays,memory,memory-management,malloc

If you try to do this in c or c++: int test[][]; you will get this error: error: declaration of 'test' as multidimensional array must have bounds for all dimensions except the first This is because test is not in fact a double ponter as you'd expect. But the compiler...

Calling free() causes my program to crash

c,crash,printf,malloc,free

You allocate space for count + 1 elements ... specifier = (char*) malloc ( (count+1) * sizeof(char)); And then go one past your array (undefined behavior): specifier[count + 1] = '\0'; ...

Include source code of malloc.c in gdb?

c,debugging,gdb,malloc

The following worked for me. Not sure whether there is a better way. Install libc6-dbg (which you have already done): sudo apt-get install libc6-dbg Install the eglibc-source package (ubuntu actually uses eglibc): sudo apt-get install eglibc-source. Unpack the tar file that was installed in /usr/src/glibc: /usr/src/glibc $ sudo tar xvf...

C - Program crashes while using malloc

c,crash,malloc,xor-linkedlist

The malloc is not the problem of your implementation. You can test this by removing the entire body of the function except of the first three lines. As Sourav Ghosh pointed out, the main issue is that you don't check if xlist, *xlist, (*xlist)->head or (*xlist)->tail is NULL before using...

Storing return values (void pointers) from malloc

c,pointers,memory-management,malloc,void-pointers

When you use malloc, you are asking for a chunk of memory in which you intend to store something. The malloc function is general-purpose, and neither knows nor cares what type of object you intend to store in the memory it has given you. The pointer-to-void (void*) return type is...

malloc can't create space for struct in queue

c,struct,queue,malloc

I see the following problems in your code: Problem 1 In insert(), you haven't allocated memory for the info of the newly allocated Node before setting values on it. You are also not setting the next of the newly constructed node in insert. rear->next remains uninitialized. If you access that...

Malloc , Realloc , Memset : Struct pointers , arrays of char, int

c,pointers,char,malloc,realloc

Error was in v_push_back implementation : v->e_array = check_a(memcpy((void*)((char*)v->e_array + (v->no_e * v->e_sz)) ,new_val, v->e_sz)); //pointer has not to be saved check_a(memcpy((void*)((char*)v->e_array + (v->no_e * v->e_sz)) ,new_val, v->e_sz)); Because memcpy returns a pointer , in this case, to the last element of the array so we would have lost access...

C array of structs segmentation fault

c,arrays,pointers,struct,malloc

The problem resides with this line : *people[*population] = p; Change it to: (*people)[*population] = p; Why are the parenthesis requried? The compiler has rules of operator precedence. When applying them, it sees your code as this: *(people[*population]) = p; which is not what you intended. Given a pointer-to-pointer Type...

correct use of malloc in function with passed uint32_t array pointer

c,malloc,uint32-t

// This works correctly and prints data as expected for (v=0;v<elementcount;v++) { printf("Method 1 %02d %u \n", v, ((uint32_t*)sched)[v]); } This is not quite right, because sched is a uint32_t**, and you allocated to *sched. And also because %u is not how you should print uint32_t. First dereference sched and...

Can we use the notation of an array for a memory allocated by malloc?

c,arrays,malloc

double *myList = malloc(3 * sizeof(double)); It is allocating memory for 3 double typed data in pointer myList. Following lines assigning double typed data on those locations. myList[0] = 1.2; myList[1] = 2.3; myList[2] = 3.4; myList[2] is equivalent *(myList+2). You need to deallocate this memory using free as follows...

How to check if memory is available for read/write operation?

c,windows,multithreading,visual-studio-2010,malloc

LOOP:do { str[c] = 'a'; c++; goto LOOP; }while( a < 2 ); This is an infinite loop, goto LOOP; is called on each iteration with no chance to check while(a < 2)...

Proper usage of malloc() and free() in c

c,malloc

The functions you have written to enter data do not use their parameters (or they use them incorrectly). Thus, it makes no sense to declare them like: char* getFirstName (char* firstName ); Within the functions, memory is allocated and a pointer to the memory is returned. Moreover, this statement: char*...

Pointing to an array inside a struct that is inside another struct

c,arrays,struct,malloc,dynamic-memory-allocation

In your code, c->name is not a valid variable name. c is a member variable of the structure variable root. There is no standalone variable named c. You can use like root->c->name = malloc( 5 ); and strcpy(root->c->name, "abc"); and printf("%s\n", root->c->name); Also, remember, sizeof(char) is guranteed to produce 1...

Realloc an array but do not lose the elements in it

c,pointers,malloc,realloc

It is OK. Just two three more things to make it perfect, Check for malloc() success before using the returned pointer. If realloc() fails, you should not be accessing the array with new dimension. After this code block, it's difficult to find out whether the allocated memory for data has...

Changing the size of a global array in the main function

c,list,struct,malloc

What you have there is static allocation and the memory is allocated on stack (actually not really on stack, since these are global variables - see the comments). It means that the size of the array needs to be known at compile time. On the other hand, you want to...

malloc() - Does it use brk() or mmap()

c,memory-management,malloc,mmap,sbrk

If we change the program to see where the malloc'd memory is: #include <unistd.h> #include <stdio.h> #include <stdlib.h> void program_break_test() { printf("%10p\n", sbrk(0)); char *bl = malloc(1024 * 1024); printf("%10p\n", sbrk(0)); printf("malloc'd at: %10p\n", bl); free(bl); printf("%10p\n", sbrk(0)); } int main(int argc, char **argv) { program_break_test(); return 0; } It's...

How to use 'new' instead of 'malloc' to allocate a 2D-array, dynamically?

c++,pointers,multidimensional-array,malloc

Well, the direct equivalent is like this: // allocate memories related to the number of rows double** matrix = new double*[row]; // allocate memories related to the number of columns of each row for(i = 0; i < row; i++) { matrix[i] = new double[column]; } // usage here //...

Malloc'ing pointer-to-pointer member of struct

c,pointers,struct,malloc,dynamic-memory-allocation

You need to allocate memory to all the pointer elements before using them. Here, d being a pointer to pointer, first you need to allocate memory for d itself, then you should go on for dereferencing d (using *d). For example, either void setp (struct mystruct *g) { g->d =...

Why the value of root is printed as 0 in main function?

c,pointers,malloc,free

You should not free() temp, because you still point to it with root, they point to the same data, hence freeing temp does free *root too. As to why it's printing 0 it's just a coincidence, because having free()ed root in the function where you allocated it, and accessing it...

Garbage with strcpy and strcat

c,malloc,strcpy,strcat

You are not allocating space for the nul terminator, a very common mistake. Suggestions: Don't use sizeof(char) it's 1 by definition. Check that malloc() did not return NULL. Always remember the nul byte. So your code would be fixed like this char *resultado = malloc(1 + tam); if (resultado ==...

pointer being realloced was not allocated

c,malloc,realloc

struct node *d = realloc(d, sizeof(d)*num); You're declaring a new d variable which shadows the previous one, and feed its yet-uninitialized value to realloc. You need to do this : struct node *newD = realloc(d, num * sizeof *d); if(!newD) { // Allocation failure, do something about it and break...

Freeing a copy of a pointer to malloc'd memory in C

c,pointers,copy,malloc,free

free does not set the pointer to NULL , or erase any memory. Instead, it marks the memory block that the pointer is pointing to as being free (i.e. not allocated). After the call to free(dummyPtr), both ptr and dummyPtr are now invalid pointers, because they do not point to...

C: Why does snprintf only writes 4 characters to my variable?

c,printf,malloc

4 is the size of the pointer on 32 bit systems, it's 8 on 64 bit systems. For pointers, sizeof always return the size of the pointer and not the size of the data it points to. Better yet, use sizeof(char) * num_characters_in_string. Use sizeof(char) * 50 in this case....

Access violation on try to fill dynamic array (large number of items)

c,arrays,pointers,malloc,dynamic-memory-allocation

"Access violation writing location 0x00000000" is explained by the manual http://man7.org/linux/man-pages/man3/malloc.3.html#RETURN_VALUE On error, these functions return NULL. Or if you prefer http://www.cplusplus.com/reference/cstdlib/malloc/. Return Value On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the...

copying the content of an dynamic array of structs into another dynamic array using memcpy

c,struct,malloc,memcpy

You need to let the compiler know what struct student is, and that's nowhere in the code. The errors mean: invalid use of undefined type ‘struct student’: You're using an undefined type dereferencing pointer to incomplete type: You're dereferencing (accessing actual value / structure) of an incomplete type, since the...

size of array allocated with malloc is showing one less than expected

c,arrays,pointers,malloc,sizeof

Look carefully, you are confusing the pointer with the array: Where bt->node[n].key is a pointer to int16_t. Thus, bt->node[n].key is a pointer to the allocated memory, not the allocated memory itself, and sizeof bt->node[n].key is sizeof <pointer to ...> which, in your system is 8 (64 bits). 8 / sizeof...

Confusion with realloc in C language [duplicate]

c,malloc,realloc

See this: $ cat test.cpp #include <stdlib.h> #include <stdio.h> int main() { void **array = (void**)malloc(sizeof(void*)*4); array[0] = (void *)"Hello"; array[1] = (void *)"World"; array[2] = (void *)"My"; array[3] = (void *)"Example"; array = (void **)realloc(array,sizeof(void*)*3); printf("%s\n",(char*)array[3]); free(array); } $ g++ test.cpp -o a -fsanitize=address $ ./a ================================================================= ==11051== ERROR:...

Why does the memory not allocate?

c,arrays,memory,malloc,word

while (words != NULL) { printf("%s\n",words); strcpy(words, word[j++]); words = strtok(NULL, delim); } free(words); Think what this code is doing; it loops until words == NULL, then tries to free (words), which, if the loop has terminated, is NULL. So, you're trying to free a NULL pointer. BTW. You...

Input returns the correct string but doesn't run the function

c,string,malloc,getline,strlen

In your code, you need to change char *cm = (char*)malloc(strlen(cmd)); to char *cm = malloc(strlen(cmd) + 1); to have space for terminating null character. The strlen() does not count the terminating null and if you don't allocate memory for holding the null during copying, you'll be facing memory overrun...

shallow copy struct got weird result on Xcode

c,malloc,free,dynamic-memory-allocation,shallow-copy

Accessing memory after you've free()d it invokes undefined behaviour. You should not be using the printf() with the free()d memory after you call free(pc1.p); ...

How to realloc a *char[] inside a while loop?

c,pointers,char,malloc,realloc

If you need to be able to increase the size of the array, use a dynamically allocated array instead of a statically defined array. Instead of: char *lesMots[10]; use char **lesMots = malloc(10*sizeof(*lesMots)); ...

Word translator program based on string comparison - heap memory assertion fails

c,arrays,string,malloc,dynamic-memory-allocation

In your code, tok is not pointing to dynamically allocated memory. You need not (and can not) free() it. Remove free(tok); from the code. From the man page of free() The free(ptr) function frees the memory space pointed to by ptr, which must have been returned by a previous call...

Malloc an array inside a struct

c,arrays,struct,malloc

You need to allocate space for the struct before you can assign to the string member: prod_t *c = malloc(sizeof(prod_t)); Also see Do I cast the result of malloc?...

Failed to add a node to linked list

c,pointers,segmentation-fault,malloc,dynamic-memory-allocation

The problem in your code is if( first==NULL){ first->next=new_s; if first is NULL, you should not dererefence it. It is logically wrong, and invokes undefined behaviour. I think, what you want instead, is something like (pseudo-code) if(first == NULL){ first = new_s; first->next = NULL; That said, current->next=new_s; current=new_s; also...

Working with malloc, char array and pointer

c++,arrays,pointers,char,malloc

Why is the size of the charBuffer 8(see first line of output) although I have allocated a size of 10? It's not. You printed out the size of a pointer to that buffer. Why I am able to add 15 characters to charBuffer although I have allocated memory for...

Initialization of Class using malloc()

c++,c,lua,malloc,new-operator

It's a bit odd to use malloc instead of new, but it is possible. You need to use placement new: void *memory = malloc(sizeof(Estructura)); Estructura *est = new(memory)Estructura; When you're finished with the object it's your responsibility to call the destructor yourself: est->~Estructura(); Everything, such as vtables, will be correctly...

c free() works when I call but not in my function

c,memory,malloc,free

You are passing the pointer to your function, which means it only has access to the local copy of this pointer. So your free(s) will free only this local copy. If you want to free a variable, that is outside of the scope of the function from which you call...

malloc and realloc array giving unexpected output

c,arrays,malloc,realloc

There is nothing wrong with the realloc. You are printing an extra uninitialized index in the last loop. Fix it by changing for (i = 0; i <= size; i++) to for (i = 0; i < size; i++) The only problem with the realloc is that you don't check...

Difference between malloc() and simple declaration in fixed sizes [duplicate]

c,double,malloc,difference

double myArray[x]; Here memory is declared on stack Declared at compile-time, hence faster Accessible only in the scope of the declaring function,( globally if declared global) Will be freed if the declaring function returns generally used when the size of array is known at compile time myArray = malloc(x*sizeof(double)); Here...

Char arrays filled with 0xCC after allocation [duplicate]

c++,malloc

Uninitialized built-in types have an in-determined value, trying to read it is undefined behavior. The actual values you can see depend on the compiler: You might for example see garbage, zeroes or (what seems to be the case in your example) some special value indicating "data uninitialized"....

Getting input into dynamically allocated memory then returning the pointer

c,arrays,pointers,malloc

your earlier code: char* get_input() { char c = 'a'; int counter = 1; while(c != '\0') { c = getc(stdin); char* d = (char)malloc(sizeof(char)*counter); *(d+counter) = c; counter++; return d; } return d; } Oh, no, no, no! You create a separate pointer address pointing to a counter size...

At what size should I malloc structs?

c,memory-management,struct,malloc

Good code gets re-used. Good code have few size limitations. Write good code. Use malloc() whenever there is anything more than trivial buffer sizes. Buffer size to write an int: The needed buffer size is at most sizeof(int)*CHAR_BIT/3 + 3. Use a fixed buffer. Buffer size to write a double...

How use index in a pointer with Struct and pointer in C

c,pointers,struct,malloc,realloc

Consider the following example: #include <stdio.h> #include <stdlib.h> struct car { char brand[50]; char model[50]; }; // dlobal variables car* garage = NULL; int cnt = 0; void doCar(){ // add counter cnt++; // add memory garage = realloc(garage, sizeof(car) * cnt); // NOTE: not malloc printf("Enter the brand: ");...

C - malloc - invalid conversion from void* to double*

c,malloc

You are using a C++ compiler. double *array=malloc(sizeof(double)*size); is valid in C. There is an implicit conversion from any object pointer type to void *. In C++ it is not valid, there is no such implicit conversion, and you need a cast: double *array= (double *) malloc(sizeof(double)*size); ...

Predefined string segfaults when copied to by strncpy()

c,segmentation-fault,malloc,strncpy

The difference is that the string literals you initialized to the pointers dst and src in the later cases are stored in the data segment. A data segment is a portion of virtual address space of a program, which contains the global variables and static variables that are initialized by...

Malloc confusion

c,pointers,malloc

In the original C language - C89/90 - calling an undeclared function is not an error. For this reason, a pre-C99 compiler will not produce any "error" due to a missing function declaration. The compiler will simply assume that function returns an int. It will also automatically and quietly "guess"...

Unable to properly free malloc of another malloc [duplicate]

c,malloc,free,dynamic-memory-allocation,calloc

In your code RESERV[i]="Iambananananananananananana"; creates the problem. It overwrites the memory allocated by malloc(). Thus, You face memory leak, because the malloc()ed pointer is lost. You cannot call free() with the changed pointer. It invokes undefined behaviour. Solution: In C, you don't assign strings, instead, you can use strcpy() to...

Dynamic Memory Allocation to Reverse Print Array of Floating Point Numbers

c,arrays,struct,floating-point,malloc

There are a lot of issues with your code. I would advise you to practice more with C basics before attempting to do this. Here is approximation of what you might have wanted to achieve with your code: #include <stdio.h> #include <string.h> // This structure can hold array of floats...

Debug error: Heap corruption detected

c,visual-studio-2010,pointers,malloc

When you try to allocate memory for string, you only allocate enough memory for a pointer (string*): self = (string*)malloc(sizeof(string*)); You should allocate sizeof(string) instead, since you want enough space to store the whole struct, not just a pointer to one. Since sizeof(string*) is smaller than sizeof(string), the other code...

Dynamic Memory Allocation

c,malloc,dynamic-memory-allocation

David Hoelzer has an excellent answer, but I wanted to follow it up a touch more: "Meta Data" for malloc is 100% implementation driven. Here is a quick overview of some implementations I have written or used: The meta data stores "next" block pointers. It stores canary values to make...

microcontroller fails at malloc

c,pointers,malloc,microcontroller

Is the malloc() working fine in other part of this code ? As you are programming an embedded device, the heap may not have been properly initialized, or it have been initialized for another custom malloc()-like function.

Why is my string truncated when copied?

c,string,pointers,malloc,sizeof

I believe, the problem is here pathlength = sizeof(pathValue)/sizeof(char); In this case, pathValue is a pointer and sizeof(pathValue) will produce a value of only the size of the pointer, not the whole amount of memory occupied by the string. What you want here is to use strlen() instead. Also, as...

Does C++ runtime always require malloc()?

c++,malloc,xilinx,standard-library,bare-metal

Reliance of a program on malloc() can occur in both C and C++, even if the program doesn't directly use them. It is a quality of implementation matter for the compiler and standard library rather than a requirement by the standards. This really depends on how the both the compiler...