Skip to main content

DeAllocating Memory

DeAllocating Memory

  • In C, memory allocated dynamically using functions like malloc, calloc, or realloc should be deallocated when it is no longer needed to prevent memory leaks.

  • Memory deallocation is performed using the free function from the <stdlib.h> header.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
// Allocate memory for an array of integers
int* dynamicArray = malloc(5 * sizeof(int));

if (dynamicArray == NULL) {
printf("Failed to allocate memory.\n");
return 1; // Error handling
}

// Use the dynamically allocated memory

// Deallocate the memory when done
free(dynamicArray);

return 0;
}

Explanation:

  • We allocate memory for an array of integers using malloc.
  • After using the dynamically allocated memory, we deallocate it using free.
  • The free function releases the memory back to the system, making it available for reuse.

Key points regarding memory deallocation:

  • The argument passed to free must be a pointer to the memory block that was previously allocated using malloc, calloc, or realloc.

  • Passing any other pointer or a pointer that has already been freed results in undefined behavior.

  • After calling free, the memory block should no longer be accessed. Any attempts to access freed memory may lead to bugs or crashes.

  • Calling free on a NULL pointer is safe and has no effect.

  • Memory deallocation should be performed for each dynamically allocated block individually. If multiple memory blocks were allocated, each one should be deallocated separately.

  • It's a good practice to set the pointer to NULL after freeing the memory to avoid mistakenly accessing freed memory.

int* dynamicArray = malloc(5 * sizeof(int));
// Use the dynamically allocated memory

free(dynamicArray);
dynamicArray = NULL; // Set the pointer to NULL