C Deallocate Memory

C Tutorial

🧹 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

free(pointer);
  • pointer 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

int x;
free(&x); // ❌ ERROR: memory not allocated dynamically
int *p = malloc(10);
free(p);
free(p); // ❌ double free — dangerous!

🛡 Best Practice: Nullify After Free

free(ptr);
ptr = NULL;

This avoids accessing invalid memory (dangling pointer).


🔥 Example: Safe Freeing with NULL Check

if (ptr != NULL) {
free(ptr);
ptr = NULL;
}

🧠 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:

int *ptr = malloc(10 * sizeof(int));
ptr = malloc(20 * sizeof(int)); // Lost reference to old memory

✅ Proper usage:

int *ptr = malloc(10 * sizeof(int));
free(ptr);
ptr = malloc(20 * sizeof(int));

Summary

Function Purpose
malloc() Allocates memory
calloc() Allocates and initializes memory to zero
realloc() Resizes allocated memory
free() Frees allocated memory (mandatory!)

You may also like...