arunbm123 wrote: ↑Sun Mar 17, 2019 9:14 am
hi
Please find the code in Image
The Heap Memory is getting low and low..
asprintf(&post_data, "%s,",pxMessage->minor);
asprintf(&post_data1, "%s",post_data);
These two lines are depleting the heap. I am freeing the memory by free()
kindly help ...
asprintf() allocates memory from the heap each time it is called. In general, you need to call free() once for each time you call asprintf(). The primary issue is that you are calling asprintf(&post_data1) in your while loop without calling free(post_data1) in the same loop. This means you allocate 10 times but then only deallocate 1 time.
Additionally, you are overwriting the pointers post_data and post_data1 in your loop. This means that you will only ever free the last allocation, without freeing all the others. Think of it something like this:
Code: Select all
char* test;
test = allocate_some_memory();
test = allocate_some_memory();
test = allocate_some_memory();
free(test);
In this example we allocate memory 3 times, and each time we assign the memory to the pointer "test". Then we call free(test) but since we overwrote test 2 times we end up only freeing the memory allocated in the third call, while the memory allocated in the first two calls is lost.
So, make sure that every time you call an allocating function like malloc, calloc, asprintf, etc. you also call free on the pointer that is returned. It must be the same pointer or you risk losing memory, or double freeing memory, which will cause a crash.
Jason