This question was asked to me in an interview.
Suppose char *p=malloc(n) assigns more than n,say N bytes of memory are allocated and free(p) is used to free the memory a
Yes, the heap manager is allowed to return a block of more than n bytes. It is completely safe (and required!) to free the returned pointer using free
, and free
will deallocate all of it.
Many heap implementations track their allocations by inserting blocks of metadata into the heap. free
will look for that metadata to determine how much memory to deallocate. This is implementation-specific, though, so there's no way to know how much malloc
gave you, and generally, you shouldn't care.