Learn C
#include "pointersmemory/calloc_realloc.h"

calloc & realloc in C

#concept

calloc(n, size) allocates for n elements and zero-fills them — array allocation plus initialization in one call, immune to count-times-size overflow bugs that plague manual multiplication. realloc(ptr, newsize) resizes an existing block, preserving contents up to the smaller size and possibly moving the block (always reassign the return — the old pointer dies on success).

The realloc protocol matters: assign to a temporary first (tmp = realloc(p, n); if (tmp) p = tmp;) or a failed resize leaks the original. Shrinking never fails in practice but the check costs nothing; growing to zero is implementation-defined — free explicitly instead.

#how it works
1

calloc zeroes

calloc(n, sizeof *a) returns zeroed storage — counters, tables, and fresh structs start clean with no init loop.

2

realloc resizes

Same contents (up to min(old, new)), possibly a new address — the dynamic-array growth primitive behind every vector.

3

Reassign via temporary

tmp = realloc(p, n); if (tmp) p = tmp; — direct assignment loses the original block when resizing fails.

4

Multiply safely

calloc's split count/size arguments avoid overflow in n * size math — one more reason to prefer it for arrays.

#example
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
int *a = calloc(2, sizeof *a);
if (!a) return 1;
int *t = realloc(a, 3 * sizeof *a);
if (!t) { free(a); return 1; }
a = t;
a[2] = 30;
printf("%d %d %d\n", a[0], a[1], a[2]);
free(a);
return 0;
}
Output
0 0 30
1calloc zeroes two ints — a[0] and a[1] start as 0 with no init loop.
2realloc grows to three slots through a temporary, preserving the zeros and protecting the original on failure.
3Setting only the new slot prints 0 0 30 — old contents intact, growth correct.
#use cases
Zero-initialized tables and counters without init loops
Growing buffers (dynamic arrays, string builders) via realloc
Failure-safe resizing through temporary-pointer protocol
Freeing the original explicitly when realloc reports failure

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.