How to Use free() in C to Release Memory
In C, use
free() to release memory previously allocated with malloc(), calloc(), or realloc(). Pass the pointer returned by these functions to free() to avoid memory leaks and keep your program efficient.Syntax
The free() function releases memory allocated dynamically. It takes a single argument, which is a pointer to the memory block you want to free.
ptr: Pointer to the memory block to be freed. This pointer must have been returned bymalloc(),calloc(), orrealloc().
c
void free(void *ptr);
Example
This example shows how to allocate memory for an integer array, use it, and then free it to avoid memory leaks.
c
#include <stdio.h> #include <stdlib.h> int main() { int *arr = malloc(5 * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed\n"); return 1; } for (int i = 0; i < 5; i++) { arr[i] = i * 10; } for (int i = 0; i < 5; i++) { printf("arr[%d] = %d\n", i, arr[i]); } free(arr); // Release the allocated memory arr = NULL; // Avoid dangling pointer return 0; }
Output
arr[0] = 0
arr[1] = 10
arr[2] = 20
arr[3] = 30
arr[4] = 40
Common Pitfalls
Common mistakes when using free() include:
- Calling
free()on a pointer that was not allocated dynamically (e.g., a local variable). - Calling
free()more than once on the same pointer (double free), which can cause crashes. - Using the pointer after it has been freed (dangling pointer).
Always set pointers to NULL after freeing to avoid accidental use.
c
#include <stdlib.h> // Wrong way: double free causes undefined behavior int *ptr = malloc(sizeof(int)); free(ptr); // free(ptr); // Uncommenting this line causes error // Right way: ptr = NULL; // After free, set pointer to NULL
Quick Reference
Remember these tips when using free():
- Only free memory allocated by
malloc(),calloc(), orrealloc(). - Do not free the same pointer twice.
- Set pointers to
NULLafter freeing. - Do not use pointers after freeing them.
Key Takeaways
Use free() to release memory allocated dynamically to prevent memory leaks.
Only pass pointers returned by malloc(), calloc(), or realloc() to free().
Never free the same pointer twice; set pointers to NULL after freeing.
Avoid using pointers after freeing to prevent undefined behavior.