How does free work in C

Thursday, May 02, 2013 , , , 0 Comments

This is very important for every C/C++ programmer to know. And most of the interviewers too ask this question.I myself had asked in many interviews, but hardly I can get a good response from the people. So I thought it would be better to post it here so that people will get to know.
char *ptr =malloc(5*sizeof(char));
The above statement will allocate 5 bytes of memory for the pointer ptr on HEAP. Most of the people that I came across specially graduates think that memory is allocated on stack which is actually not true.

So after you use ptr in your code and get the task done you have to delete or free the you write this for it.
Remember, you are not passing 5 bytes to free as an argument, but how come free function know that it has to free 5 bytes? When you call malloc(), you specify the amount of memory to allocate. The amount of memory actually used is slightly more than this, and includes extra information that records (at least) how big the block is. You can't (reliably) access that other information - and nor should you . When you call free(), it simply looks at the extra information to find out how big the block is.

This is the logic behind this magic(at least for a programmer this is a magic provided by the standard).
also see the link in c-faqs:
How does free know how many bytes to free?
Same principle is followed for delete and new.