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 allocated to p.
can heap manager perform such faulty allocation ? what happens now, will n bytes are freed or N bytes are freed?
is there any method to find how much memory is freed?
EDIT
is there any method to find how much memory is freed?
better than nothing,
mallinfo() can shed some light as pointed by "Fred Larson"
If we allocate memory using malloc, it should be deleted using free. If we allocate memory using new, it should be deleted using delete.
If we don't deallocate the dynamic memory, it will reside in the heap section.It is also called memory leak. It will reduce the system performance by reducing the amount of available memory.
When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With