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.
- C Program to print numbers from 1 to N without using semicolon?
- Storage Classes in C
- Enumeration (or enum) in C
- Interesting Facts about Macros and Preprocessors in C
- Commonly Asked C Programming Interview Questions | Set 1
- How to deallocate memory without using free() in C?
- Memory Layout of C Programs
- Multidimensional Pointer Arithmetic in C/C++
- fseek() vs rewind() in C
- Use of realloc()
- delete and free() in C++
- calloc() versus malloc()
- What is Memory Leak? How can we avoid?
- Understanding "extern" keyword in C
- What is the best way in C to convert a number to a string?