ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-202 min read

Master dynamic heap memory allocation in C with malloc, calloc, realloc, and free. Step-by-step memory safety and leak prevention guide.

Dynamic Memory in Standard C

In C, variables on the stack have fixed compile-time lifespans. Dynamic memory allocation allows requesting variable-sized memory buffers from the system heap at runtime using functions from <stdlib.h>.

FunctionPurposeInitial Content
malloc(size)Allocates uninitialized memory bufferIndeterminate (garbage values)
calloc(n, size)Allocates memory for n elementsZero-initialized
realloc(ptr, size)Resizes an existing heap allocationPreserves previous data
free(ptr)Deallocates heap memory blockReturns block to OS

Working C Code Example

c (ISO Standard)
#include <stdio.h>
#include <stdlib.h>

int main() {
    int initialSize = 3;
    int expandedSize = 5;

    /* 1. Allocate initial array with calloc (zero-initialized) */
    int *numbers = (int*)calloc(initialSize, sizeof(int));
    if (numbers == NULL) {
        fprintf(stderr, "Heap allocation failed.\n");
        return 1;
    }

    numbers[0] = 10;
    numbers[1] = 20;
    numbers[2] = 30;

    printf("Initial Buffer (size %d):\n", initialSize);
    for (int i = 0; i < initialSize; i++) {
        printf("  numbers[%d] = %d\n", i, numbers[i]);
    }

    /* 2. Resize buffer using realloc */
    int *temp = (int*)realloc(numbers, expandedSize * sizeof(int));
    if (temp == NULL) {
        free(numbers);
        fprintf(stderr, "Reallocation failed.\n");
        return 1;
    }
    numbers = temp;
    numbers[3] = 40;
    numbers[4] = 50;

    printf("\nResized Buffer (size %d):\n", expandedSize);
    for (int i = 0; i < expandedSize; i++) {
        printf("  numbers[%d] = %d\n", i, numbers[i]);
    }

    /* 3. Free memory to prevent memory leaks */
    free(numbers);
    numbers = NULL; /* Avoid dangling pointer */

    return 0;
}

Sample Output

text (ISO Standard)
Initial Buffer (size 3):
  numbers[0] = 10
  numbers[1] = 20
  numbers[2] = 30

Resized Buffer (size 5):
  numbers[0] = 10
  numbers[1] = 20
  numbers[2] = 30
  numbers[3] = 40
  numbers[4] = 50

Complexity Analysis

  • Time Complexity: O(1) allocation; O(n) if realloc needs to copy memory to a new address.
  • Space: Allocated dynamically on the system heap.

Related C Examples & Tutorials