Search code examples
cmallocfreedynamic-memory-allocationcalloc

How is the size of dynamic memory tracked in C


I understand that using calloc() and malloc() will allocate the specific amount of memory on the heap and return a pointer to the beginning of the allocation.

I also know that free( poinerVar) will de-allocate (free up the allocated memory). However, I cannot visualize how free() knows the amount of memory to de-allocate. Managed languages such as C#, Java keeps track of it's objects for garbage collection, but C surely does not (as far I know).

What is happening at the memory management level that enables the de-allocating of memory using free and passing it just the pointer variable.


Solution

  • The usual approach here is that memory allocation functions are storing metadata about allocated space before actual memory chunk.

    In that way, free() just can read memory in front of the actual allocated block and it can find out how much memory should it actually deallocate.