Learn C
#include "pointersmemory/malloc_free.h"

malloc & free in C

#concept

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.

#how it works
1

Allocate by count times size

malloc(n * sizeof *a) — element count times dereferenced-pointer size keeps type changes from breaking the math.

2

Memory is uninitialized

malloc returns garbage-filled bytes, not zeros — initialize before reading (or use calloc).

3

Check for NULL

if (!a) handles exhaustion — dereferencing NULL segfaults, and OOM is real on constrained systems.

4

Free exactly once

free(a); then stop touching a (set a = NULL to enforce it) — leaks waste, double-frees corrupt.

#example
#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;
}
Output
10 20 30
1malloc reserves 3 ints sized by the object expression — n could have come from input just as well.
2The NULL check guards exhaustion before any use; the loop then initializes every slot.
3Values print, free releases exactly once, and the program exits clean.
#use cases
Runtime-sized arrays from input, files, or computation
Long-lived structures outliving their creating function
NULL-checked allocation in every code path
free-once discipline with NULL-after-free habits

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.