C/C++ Arena

malloc and free: dynamic memory in C

How to allocate memory on the heap in C with malloc, calloc and realloc, check for failure, and free it correctly.

Local variables live on the stack and vanish when their function returns. When you need memory whose size is only known at run time, or that must outlive a function, ask for it on the heap:

Write sizes as n * sizeof *p so they stay right if the type changes.

Example

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

int main(void) {
    int n = 5;
    int *squares = malloc(n * sizeof *squares);
    if (squares == NULL) return 1;
    for (int i = 0; i < n; i++) squares[i] = i * i;
    printf("%d\n", squares[4]);
    free(squares);
    return 0;
}

Output:

16

Watch it run: An array on the heap

Practice it