Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How does free() know the size of memory to be deallocated?
The free() function is used to deallocate memory that was allocated using malloc(), calloc(), or realloc(). The syntax of free() is simple − it only takes a pointer as an argument and deallocates the memory.
Syntax
void free(void *ptr);
The interesting question is: how does free() know the size of the memory block to deallocate when it only receives a pointer?
How free() Determines Memory Block Size
When you allocate memory using dynamic memory allocation functions, the memory management system stores metadata about each allocated block. This metadata typically includes the size of the allocated block and is stored in a header just before the user data.
Example: Demonstrating Memory Allocation
Here's an example that shows how memory allocation works and how free() operates ?
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr1, *ptr2;
/* Allocate memory for 5 integers */
ptr1 = (int*)malloc(5 * sizeof(int));
/* Allocate memory for 10 integers */
ptr2 = (int*)malloc(10 * sizeof(int));
if (ptr1 == NULL || ptr2 == NULL) {
printf("Memory allocation failed<br>");
return 1;
}
printf("Memory allocated successfully<br>");
printf("ptr1 points to: %p<br>", (void*)ptr1);
printf("ptr2 points to: %p<br>", (void*)ptr2);
/* free() automatically knows the size to deallocate */
free(ptr1); /* Frees 5 * sizeof(int) bytes */
free(ptr2); /* Frees 10 * sizeof(int) bytes */
printf("Memory deallocated successfully<br>");
return 0;
}
Memory allocated successfully ptr1 points to: 0x55a1b2c3d010 ptr2 points to: 0x55a1b2c3d030 Memory deallocated successfully
How It Works
The memory management system works as follows:
-
Allocation: When
malloc()is called, it allocates more memory than requested to store metadata (usually the block size) in a header. - Pointer Return: The returned pointer points to the user data area, not the beginning of the entire allocated block.
-
Deallocation: When
free()is called, it moves backward from the given pointer to read the header and determine the block size. - Cleanup: The entire block (header + user data) is marked as available for future allocations.
Key Points
- The actual implementation varies between different C libraries and operating systems.
- Never call
free()on a pointer that wasn't returned bymalloc(),calloc(), orrealloc(). - Always set pointers to
NULLafter callingfree()to avoid dangling pointers. - The metadata overhead is typically small (4-8 bytes on most systems).
Conclusion
The free() function determines the size of memory to deallocate by reading metadata stored in a hidden header just before the user data. This elegant design allows free() to work with just a pointer, making memory management simpler for programmers.
