Search code examples
cmemory-managementmallocfree

Why is there not a function in C that returns size of memory allocated pointed to by a pointer?


After searching around for a bit on how deallocation (via free) after allocation (via something like malloc) works, I'm left puzzled.

Reading around, sources say that when memory is allocated, it actually has one word more allocated which stores the size of the allocation. This is what free uses to deallocate the memory. But with this information arises another question which I can not find the answer to anywhere: If the size of memory allocated is stored somewhere, why is there not a function or method in C that can give us the size of memory allocated via something like malloc?


Solution

  • The C standard only specifies the functions needed to allocate and free memory. This means that how the heap is managed is a implementation detail of the standard library on your system. How Linux does it is likely very different from Microsoft's implementation.

    That being said, sometimes these implementations expose additional functions that expose the internal state of the heap. For example, Linux has a function called malloc_usable_size which is passed a pointer to allocated memory and returns the number of bytes that may be written at that address.

    Still, it's best not to depend on system specific functions like that. Your program should have some way of keeping track of how much space a malloc'ed block of memory points to.