top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How does free() know how much memory to release?

+1 vote
139 views
How does free() know how much memory to release?
posted Jul 22, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

While allocating memory through malloc/calloc function system allocates memory few bytes more which contains the information like size of allocated memory and etc.

When free is called for a valid address, it search through the list of allocated block. if It finds then deallocate the memory with the stored size.

For Example -
Say you are allocating 10 Bytes, system allocates 4+10 bytes and store the value 14 in first 4 bytes. Then return the pointer after moving 4 bytes forward. So the user get only 10 bytes.

In free you provide the pointer, control goes back by 4 bytes and read the first 4 bytes to get the length and free the 14 bytes.

answer Jul 22, 2014 by Salil Agrawal
...