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, that's what happens almost every time do you a malloc()
. The malloc
block header contains information about the the size of the block, and when free()
is called, it returns that amount back to the heap. It's not faulty, it's expected operation.
A simple implementation might, for instance, store just the size of the block in the space immediately preceding the returned pointer. Then, free()
would look something like this:
void free(void *ptr)
{
size_t *size = (size_t *)ptr - 1;
return_to_heap(ptr, *size);
}
Where return_to_heap()
is used here to mean a function that does the actual work of returning the specified block of memory to the heap for future use.