I suspect the answer to my question is language specific, so I’d like to know about C and C++. When I call free() on a buffer or use delete[], how does the program know how much memory to free?
Where is the size of the buffer or of the dynamically allocated array stored and why isn’t it available to the programmer as well?
The heap keeps track of all memory blocks, both allocated and free, specifically for that purpose. Typical (if naive) implemenation allocates memory, uses several bytes in the beginning for bookkeeping, and returns the address past those bytes. On subsequent operations (free/realloc), it would subtract a few bytes to get to the bookkeeping area.
Some heap implementations (say, Windows’
GlobalAlloc()) let you know the block size given the starting address. But in the C/C++ RTL heap, no such service.Note that the malloc() sometimes overallocates memory, so the information about
mallocated block size would be of limited utility. C++ new[]’ed arrays, that’s a whole another matter – for those, knowing exact array size is essential for array destruction to work properly. Still, there’s no such thing in C++ as adynamic_sizeofoperator.