Dynamic Memory Allocation in C (malloc, calloc, realloc, free with Examples)


This tutorial explains dynamic memory allocation in C, which allows programmers to allocate memory at runtime. It covers malloc, calloc, realloc, and free with syntax and practical examples for efficient memory management.

1. What is Dynamic Memory Allocation

  1. Dynamic memory allocation allows memory to be allocated during runtime.
  2. Useful when the size of data is unknown at compile time.
  3. Functions used: malloc(), calloc(), realloc(), free().
  4. Requires #include <stdlib.h>.

2. malloc() – Memory Allocation

  1. Allocates memory of given size and returns a void pointer.
  2. Syntax:

ptr = (cast_type*) malloc(size_in_bytes);

Example


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

int main() {
int *ptr;
int n = 5;

ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL) {
printf("Memory not allocated.\n");
return 1;
}

for(int i = 0; i < n; i++)
ptr[i] = i + 1;

printf("Elements: ");
for(int i = 0; i < n; i++)
printf("%d ", ptr[i]);

free(ptr); // free allocated memory
return 0;
}

Output:


Elements: 1 2 3 4 5

3. calloc() – Contiguous Allocation

  1. Allocates memory for array of elements and initializes all to 0.
  2. Syntax:

ptr = (cast_type*) calloc(num_elements, size_of_each_element);

Example


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

int main() {
int *ptr, n = 5;

ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Memory not allocated.\n");
return 1;
}

printf("Elements after calloc: ");
for(int i = 0; i < n; i++)
printf("%d ", ptr[i]);

free(ptr);
return 0;
}

Output:


Elements after calloc: 0 0 0 0 0

4. realloc() – Reallocate Memory

  1. Changes the size of previously allocated memory.
  2. Syntax:

ptr = (cast_type*) realloc(ptr, new_size_in_bytes);

Example


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

int main() {
int *ptr, n = 3;

ptr = (int*) malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
ptr[i] = i + 1;

// Increase size to 5
ptr = (int*) realloc(ptr, 5 * sizeof(int));
ptr[3] = 4;
ptr[4] = 5;

printf("Elements after realloc: ");
for(int i = 0; i < 5; i++)
printf("%d ", ptr[i]);

free(ptr);
return 0;
}

Output:


Elements after realloc: 1 2 3 4 5

5. free() – Free Allocated Memory

  1. Frees memory allocated by malloc, calloc, or realloc to avoid memory leaks.
  2. Syntax:

free(ptr);

Key Notes

  1. Always check if pointer is NULL before accessing memory.
  2. After free(), set pointer to NULL to avoid dangling pointer.

free(ptr);
ptr = NULL;

6. Key Points to Remember

  1. Use malloc() for single allocation, calloc() for array with zero initialization
  2. Use realloc() to resize memory dynamically
  3. Always free memory after use
  4. Dynamic memory is essential for efficient memory management in large or variable-size programs