Heap memory depleting

User avatar
arunbm123
Posts: 96
Joined: Fri Feb 23, 2018 5:36 am

Heap memory depleting

Postby arunbm123 » 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 ...
Image
Attachments
esp.png
esp.png (14.82 KiB) Viewed 5153 times

vonnieda
Posts: 145
Joined: Tue Nov 07, 2017 3:42 pm

Re: Heap memory depleting

Postby vonnieda » Sun Mar 17, 2019 6:06 pm

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 ...
Image
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

User avatar
arunbm123
Posts: 96
Joined: Fri Feb 23, 2018 5:36 am

Re: Heap memory depleting

Postby arunbm123 » Mon Mar 18, 2019 4:11 am

thanks

Yes figured it out ............

Who is online

Users browsing this forum: Google [Bot] and 126 guests