C Language
8. Dynamic Memory AllocationAdvanced11 min read

Dynamic Memory Allocation: malloc, calloc, realloc & free

Allocate memory at runtime on the Heap using malloc, calloc, realloc, and prevent memory leaks with free.

Key Takeaways & Core Concepts
  • Stack memory is fixed and scoped to function execution; Heap memory persists until explicitly freed.
  • malloc(size) allocates uninitialized raw bytes on the heap.
  • calloc(num, size) allocates contiguous memory and initializes all bytes to zero.
  • realloc(ptr, new_size) dynamically expands or contracts previously allocated heap memory.
  • free(ptr) releases heap memory back to the operating system allocator.
  • Failing to free heap memory leads to progressive memory leaks.

The 4 Pillars of Dynamic Memory (<stdlib.h>)

When data sizes cannot be predicted ahead of time (such as dynamic user inputs, network sockets, or resizable lists), dynamic memory allocation is essential. C provides 4 core functions in <stdlib.h>:

Always Check for NULL After Allocation

If system memory is exhausted, malloc and calloc return NULL. Always verify `if (ptr == NULL)` before accessing the allocated memory!

FunctionStandard SignaturePurpose & Allocation Behaviour
malloc()void* malloc(size_t size)Allocates 'size' bytes on the Heap. Leaves memory uninitialized (contains random garbage bytes).
calloc()void* calloc(size_t num, size_t size)Allocates 'num * size' bytes and clears every single byte to zero (0).
realloc()void* realloc(void *ptr, size_t new_size)Expands or contracts an existing heap block. Relocates data if contiguous space is unavailable.
free()void free(void *ptr)Releases the allocated heap block back to the OS allocator. Does NOT nullify the pointer.

Dynamic Array with Resizing

Here is how modern C programs create expandable dynamic arrays on the heap:

Creating and Resizing a Dynamic Array
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(void) {
5 int capacity = 3;
6 int *arr = (int*)malloc(capacity * sizeof(int));
7 if (arr == NULL) {
8 fprintf(stderr, "Memory allocation failed!\n");
9 return 1;
10 }
11
12 // Populate initial items
13 arr[0] = 100;
14 arr[1] = 200;
15 arr[2] = 300;
16
17 printf("Initial capacity: %d items\n", capacity);
18
19 // Need more room? Expand capacity with realloc
20 capacity = 5;
21 int *temp = (int*)realloc(arr, capacity * sizeof(int));
22 if (temp == NULL) {
23 free(arr); // Free original if resize fails
24 return 1;
25 }
26 arr = temp;
27
28 arr[3] = 400;
29 arr[4] = 500;
30
31 printf("Expanded array items:\n");
32 for (int i = 0; i < capacity; i++) {
33 printf("arr[%d] = %d\n", i, arr[i]);
34 }
35
36 // Clean up
37 free(arr);
38 arr = NULL;
39 printf("Memory cleanly freed!\n");
40
41 return 0;
42}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
42 lines
Note: realloc safely preserved existing elements [100, 200, 300] while extending capacity to 5 items.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 2 correct(0 attempted)

1

What is the primary difference between malloc() and calloc()?

Intermediate
2

What happens if you do not call free() on memory allocated with malloc() before a long-running program continues?

Intermediate