calloc & realloc in C
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.
calloc zeroes
calloc(n, sizeof *a) returns zeroed storage — counters, tables, and fresh structs start clean with no init loop.
realloc resizes
Same contents (up to min(old, new)), possibly a new address — the dynamic-array growth primitive behind every vector.
Reassign via temporary
tmp = realloc(p, n); if (tmp) p = tmp; — direct assignment loses the original block when resizing fails.
Multiply safely
calloc's split count/size arguments avoid overflow in n * size math — one more reason to prefer it for arrays.
#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;}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.