We are going to explain manual memory management in C, which involves allocating and deallocating memory explicitly by the programmer.
Key points:
- Memory allocation from the heap in C is done using
malloc, calloc, realloc.
- Memory deallocation is done using
free.
- Memory leak: when memory is allocated but not deallocated, leading to wasted memory.
- Dangling pointer: a pointer that points to memory that has been deallocated.
- Double free: calling
free on the same pointer more than once, which leads to undefined behavior.
Let's break down the explanation and provide examples for each term.
Manual Memory Management in C
In languages like C, memory is managed explicitly by the programmer rather than automatically (as in garbage-collected languages). This gives fine-grained control but requires careful handling to avoid errors.
Heap Allocation Functions
Memory is dynamically allocated from the heap (a region of memory for runtime allocations):
malloc(size_t size) – Allocates size bytes; returns void* (or NULL on failure). Memory is uninitialized.
calloc(size_t nmemb, size_t size) – Allocates nmemb * size bytes; initializes to zero.
realloc(void *ptr, size_t new_size) – Resizes previously allocated memory block (may move it).
free(void *ptr) – Deallocates memory previously allocated by malloc/calloc/realloc. After free(ptr), ptr becomes dangling (see below).
Example:
int *arr = malloc(10 * sizeof(int)); // Allocate array of 10 ints
if (arr == NULL) { /* handle error */ }
// Use arr...
free(arr); // Release memory
Memory Leak
A memory leak occurs when allocated memory is never deallocated, wasting heap space. Common causes: losing the pointer to allocated memory or forgetting free().
Example:
void leak_example() {
int *data = malloc(100 * sizeof(int));
// ... use data ...
// Oops: no free(data) -> memory leaked when function returns
}
Impact: Accumulates over time, potentially exhausting system memory.
Dangling Pointer
A dangling pointer points to memory that has been deallocated (via free). Using it leads to undefined behavior (crashes, data corruption).
Example:
int *dangling_example() {
int x = 42;
int *ptr = &x; // ptr points to stack variable
return ptr; // ptr becomes dangling after function returns (x out of scope)
}
int *dangling_free_example() {
int *p = malloc(sizeof(int));
*p = 10;
free(p); // p now points to freed memory
return p; // Returning dangling pointer
}
Fix: After free(p), set p = NULL; (NULL pointer is safe to check).
Double Free Error
Double free occurs when free() is called more than once on the same pointer. This corrupts heap metadata, causing crashes or security vulnerabilities.
Example:
void double_free_error() {
int *p = malloc(sizeof(int));
free(p);
free(p); // ERROR: double free! Undefined behavior.
}
Fix: After freeing, set pointer to NULL (since free(NULL) is safe and does nothing):
free(p);
p = NULL; // Prevent accidental reuse
Key Takeaways
- Every
malloc/calloc/realloc must have exactly one matching free.
- Never use memory after
free – set pointer to NULL if it might be reused.
- Never
free a pointer not from heap allocation (e.g., stack variables).
- Use tools like Valgrind or AddressSanitizer to detect leaks, dangling pointers, and double frees.
Safe Pattern:
int *safe_example() {
int *p = malloc(sizeof(int) * 10);
if (!p) return NULL; // Check allocation
// ... use p ...
free(p);
return NULL; // Optional: reset p if used elsewhere
}