IntermediateLesson 11 of 18
Dynamic Memory: malloc & free – C
Requesting, resizing and releasing memory at runtime – and avoiding typical mistakes.
Local variables live on the stack and disappear at the end of the function. For data whose size is only known at runtime or that should live longer, you request memory from the heap: malloc (uninitialized), calloc (filled with 0), realloc (change size). Whatever you request, you must release again with free.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
int *a = malloc(n * sizeof *a); // sizeof *a instead of sizeof(int): type-safe
if (a == NULL) {
fprintf(stderr, "Out of memory\n");
return 1;
}
for (int i = 0; i < n; i++) a[i] = i * i;
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
free(a);
a = NULL; // prevents accidental further use
return 0;
}realloc enlarges or shrinks a block and copies it elsewhere if necessary. If it fails, it returns NULL – the old block stays valid! So store the result in a helper variable first:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *b = calloc(4, sizeof *b); // 4 zeros
if (b == NULL) return 1;
int *tmp = realloc(b, 8 * sizeof *b); // grow to 8 elements
if (tmp == NULL) {
free(b); // the old block is still there
return 1;
}
b = tmp;
int summe = 0;
for (int i = 4; i < 8; i++) b[i] = i; // initialize the new elements
for (int i = 0; i < 8; i++) summe += b[i];
printf("Sum: %d\n", summe); // 22
free(b);
return 0;
}A growing array ("vector") doubles its capacity when it is full – this makes appending very fast on average:
#include <stdio.h>
#include <stdlib.h>
typedef struct { int *daten; size_t len, cap; } Vec;
int vec_push(Vec *v, int x) {
if (v->len == v->cap) {
size_t neu = v->cap ? v->cap * 2 : 4;
int *tmp = realloc(v->daten, neu * sizeof *tmp);
if (tmp == NULL) return -1;
v->daten = tmp;
v->cap = neu;
}
v->daten[v->len++] = x;
return 0;
}
int main(void) {
Vec v = {NULL, 0, 0};
for (int i = 1; i <= 10; i++) {
if (vec_push(&v, i) != 0) { free(v.daten); return 1; }
}
printf("len=%zu cap=%zu last=%d\n", v.len, v.cap, v.daten[v.len - 1]);
free(v.daten);
return 0;
}WarningThe four classics: memory leak (no
free), use-after-free (access after free), double free (calling free twice) and overflow (writing more than was requested). Rule of thumb: every malloc has exactly one free – and someone is clearly the "owner" of the block.Tip
free(NULL) is allowed and does nothing. Set pointers to NULL after free – a later access then crashes immediately and traceably instead of silently corrupting data.