Monday 2 September 2019

c++ - 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"



Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...