Question

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.

Was it helpful?

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.

OTHER TIPS

The C standard(s) do not say how that malloc/free works under the covers. Only the external behavior. If you really want to understand it, you need to look at a specific implementation. Check out an open source libc, like the one used by GNU/gcc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top