Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc().
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( )
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to deallocate memory without using free() in C?
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- what happens when you don't free memory after using malloc()
- Four File Handling Hacks which every C/C++ Programmer should know
- delete and free() in C++
- What happens if we mix new and free in C++?
- Get the stack size and set the stack size of thread attribute in C
- Does C support function overloading?
- How does "void *" differ in C and C++?
- Does C++ compiler create default constructor when we write our own?
- Write a C program that does not terminate when Ctrl+C is pressed
- When does compiler create default and copy constructors in C++?
- Does overloading work with Inheritance?
- How does Duff's Device work?
- C program that does not suspend when Ctrl+Z is pressed
- Why variable name does not start with numbers in C ?
- Why does sizeof(x++) not increment x in C?
- How does a C program executes?
- What does main() return in C and C++?
- How does Volatile qualifier of C works in Computing System