How does free know the size of memory to be deleted?

(Last Updated On: March 4, 2017)

Answer is little bit tricky but simple to how does free know the size of memory to be deleted or deallocated?  . Elaborating interview question as, since, we only pass a pointer or address to free (void*ptr) function and not size then how does free() function in C/C++ program know the size of memory to be de-allocated.

Yes, we pass only pointer / address and not size of the allocated memory to free (void* p) function for de-allocation.

In fact, malloc() and free() functions implementation varies compiler to compiler. They can implement different mechanism to free dynamically allocated memory. For example. It can be implemented by memory section marking mechanism or using extra bytes to store the size of memory besides requested memory by the user.

Marking Mechanism to free memory in C/C++:

Internally, the free () function’s job is to marking dynamically allocated memory section as “false” or 0.

When we allocate memory of particular size using malloc() function, it returns address of allocated memory and mark that section as true or 1 in one of the table/structure.

So, function free (), just need to know the address and not size of the dynamically allocated memory. Marking memory as false or 0 is known as de-allocation of memory.

Extra bytes allocation mechanism to free memory in C/C++:

During dynamic memory allocation , a chunk of memory (extra bytes+ requested size) with contiguous extra bytes besides requested size by user will be allocated from the heap to store the size of request memory. And by adjusting the pointer, actual request size of memory will be return to the user.

When free (void* p) method get called, it just go to that address pointed by the pointer and read the size of allocated memory from extra bytes memory to be freed.

Note: Same internal working for allocation and de-allocation is applied to new and delete operator as new/delete internally calls malloc and free method besides mechanism of calling constructor and destructor respectively.