malloc & free in C
malloc allocates uninitialized heap bytes at run time: int *a = malloc(n * sizeof *a); reserves room for n ints whose count may come from input or files. Heap memory outlives the allocating function (unlike locals) and dies only at free(a) — manual lifetime control with manual responsibility.
The contract has three clauses: check for NULL (allocation can fail), use exactly the allocated span (overflows corrupt the heap silently), and free exactly once (leaks and double-frees are the twin sins). Sized as count-times-element with sizeof on the object, not the type, allocations stay correct through refactors.
Allocate by count times size
malloc(n * sizeof *a) — element count times dereferenced-pointer size keeps type changes from breaking the math.
Memory is uninitialized
malloc returns garbage-filled bytes, not zeros — initialize before reading (or use calloc).
Check for NULL
if (!a) handles exhaustion — dereferencing NULL segfaults, and OOM is real on constrained systems.
Free exactly once
free(a); then stop touching a (set a = NULL to enforce it) — leaks waste, double-frees corrupt.
#include <stdio.h>#include <stdlib.h> int main(void) { int n = 3; int *a = malloc(n * sizeof *a); if (!a) return 1; for (int i = 0; i < n; ++i) a[i] = (i + 1) * 10; printf("%d %d %d\n", a[0], a[1], a[2]); free(a); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.