Bloomberg Interview Question

How many bytes are actually allocated by malloc(n)? How does free() know how many bytes to free?

Interview Answer

Anonymous

Dec 6, 2011

The second part of the question itself is the answer to the first one. The number of bytes allocated by malloc depends on the implementation of malloc and underlying architecture. Usually if asked for n sized block, malloc would return something more than n. This extra memory is used for bookkeeping purposes, like the size of the block, so when free is called on that block, heap manager can know from that information how many bytes were allocated in order to free them.