The Wayback Machine - https://web.archive.org/web/20240118165851/https://www.geeksforgeeks.org/g-fact-88/
Open In App
Related Articles

How does free() know the size of memory to be deallocated?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc().




void free(void *ptr);


Note that the free function does not accept size as a parameter. How does free() function know how much memory to free given just a pointer?

Following is the most common way to store size of memory so that free() knows the size of memory to be deallocated.
When memory allocation is done, the actual heap space allocated is one word larger than the requested memory. The extra word is used to store the size of the allocation and is later used by free( )

References:
http://www.cs.cmu.edu/afs/cs/academic/class/15213-f10/www/lectures/17-allocation-basic.pptx
http://en.wikipedia.org/wiki/Malloc

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 28 May, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads