Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens when tried to free memory allocated by heap manager, which allocates more than asked for?

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"

like image 582
Rozuur Avatar asked Feb 25 '10 17:02

Rozuur


People also ask

What will happen if I allocate memory using malloc and free it using free or allocate using new and free it using Delete?

If we allocate memory using malloc, it should be deleted using free. If we allocate memory using new, it should be deleted using delete.

What happens if heap memory is not freed?

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.

What happens when heap memory is full?

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.


1 Answers

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.

like image 185
Carl Norum Avatar answered Sep 20 '22 22:09

Carl Norum