C Deallocate Memory
🧹 C Deallocate Memory (free())
In C Deallocate Memory, 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
-
pointera 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 allocate data.
-
Before exiting a function (if memory will not be use).
-
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!) |
