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

free(pointer);
  • pointer must be a memory address previously allocated using:

    • malloc()

    • calloc()

    • realloc()


๐Ÿ“Œ Example: Allocating and Freeing Memory

#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(5 * sizeof(int));

if (ptr == NULL) {
printf(“Memory allocation failed!\n”);
return 1;
}

for (int i = 0; i < 5; i++) {
ptr[i] = i + 1;
}

printf(“Stored Values:\n”);
for (int i = 0; i < 5; i++) {
printf(“%d “, ptr[i]);
}

// Free the allocated memory
free(ptr);

printf(“\nMemory freed successfully!”);

return 0;
}


๐Ÿšจ 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 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:

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!)

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *