Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › C

Dynamic Memory Allocation in C

Sometimes you only know how much memory you need while the program runs (e.g. n comes from input). C lets you request memory from the heap and give it back yourself.

Memory layout of a C program

Segment Holds Managed by
Text compiled code OS
Data / BSS global and static variables compiler
Heap malloc/calloc/realloc memory you (free)
Stack local variables, function calls automatic

The heap grows as you allocate; the stack grows with each function call.

The four functions (<stdlib.h>)

Function Does Initialises?
malloc(bytes) allocates a block ❌ garbage values
calloc(n, size) allocates n × size bytes ✅ all zero
realloc(ptr, newBytes) grows/shrinks a block (may move it) new part not initialised
free(ptr) gives the block back —

All allocation functions return NULL if memory is not available — always check.

malloc

int n;
scanf("%d", &n);
int *a = (int*)malloc(n * sizeof(int));   // the cast is optional in C
if (a == NULL) {
    printf("Out of memory\n");
    return 1;
}
for (int i = 0; i < n; i++) a[i] = i * i;
free(a);
a = NULL;                                  // avoid a dangling pointer

Always use sizeof(type) — never assume int is 4 bytes.

calloc

int *count = calloc(26, sizeof(int));      // 26 zeros — handy for frequency arrays

realloc — a growing array

int cap = 2, size = 0;
int *arr = malloc(cap * sizeof(int));
for (int x = 1; x <= 10; x++) {
    if (size == cap) {
        cap *= 2;                                         // double the capacity
        int *tmp = realloc(arr, cap * sizeof(int));
        if (!tmp) { free(arr); return 1; }                // keep the old block on failure
        arr = tmp;
    }
    arr[size++] = x;
}
free(arr);

Doubling gives O(1) amortised appends — exactly how C++ vector and Java ArrayList work.

Dynamic 2D array

int rows = 3, cols = 4;
int **grid = malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) grid[i] = calloc(cols, sizeof(int));
grid[1][2] = 7;
for (int i = 0; i < rows; i++) free(grid[i]);   // free each row, then the array of rows
free(grid);

Common bugs

Bug Example Result
Memory leak allocating in a loop and never calling free memory use keeps growing
Dangling pointer using a pointer after free undefined behaviour
Double free calling free twice on the same pointer crash / corruption
Buffer overflow writing a[n] in an array of n overwrites other data
Wrong size malloc(n) instead of malloc(n * sizeof(int)) too little memory
Lost pointer p = malloc(...); p = malloc(...); first block leaked
char *s = malloc(6);
strcpy(s, "hello");     // 5 letters + '\0' = 6 bytes ✅ (forgetting '\0' is a classic overflow)

Tools: run with valgrind ./a.out or compile with -fsanitize=address to find leaks and invalid accesses.

Stack vs heap

Stack Heap
Allocation automatic manual (malloc/free)
Speed very fast slower
Size small (a few MB) large
Lifetime until the function returns until you free it
Errors stack overflow leaks, fragmentation

C vs C++

C++ uses new / delete (calls constructors/destructors) — and in modern C++ you rarely call them yourself: use vector, string, unique_ptr, shared_ptr (RAII frees memory automatically).

Interview one-liners

More C notes