C Deallocate Memory
๐งน C Deallocate Memory (free())
In C programming, dynamic memory allocation is done using functions like malloc(), calloc(), and realloc().
However, this memory is not automatically released โ you must manually free it using the free() function.
If you forget to free allocated memory, it causes a memory leak, which can slow down or crash programs, especially long-running ones.
โ Syntax
-
pointermust be a memory address previously allocated using:-
malloc() -
calloc() -
realloc()
-
๐ Example: Allocating and Freeing Memory
๐จ Important Rules for free()
| Rule | Explanation |
|---|---|
| Only free allocated memory | Do NOT free stack variables or already freed memory |
| Free once | Calling free() multiple times on the same pointer causes undefined behavior |
| Set pointer to NULL after freeing | Prevents accidental access (dangling pointer) |
โ Example of Incorrect Freeing
๐ก Best Practice: Nullify After Free
This avoids accessing invalid memory (dangling pointer).
๐ฅ Example: Safe Freeing with NULL Check
๐ง When to Free Memory?
Free memory when:
-
You’re done using the allocated data.
-
Before exiting a function (if memory will not be used).
-
Before reassigning a pointer to new memory (to avoid leaks).
๐งช Mini Example Showing Memory Leak Fix
โ Leaking memory:
โ Proper usage:
Summary
| Function | Purpose |
|---|---|
malloc() |
Allocates memory |
calloc() |
Allocates and initializes memory to zero |
realloc() |
Resizes allocated memory |
free() |
Frees allocated memory (mandatory!) |
