Back to Blog

C in 100 Seconds: calloc and realloc | Episode 21

Daryl WongDaryl Wong

Video: C in 100 Seconds: calloc realloc — Zero Init and Resize | Episode 21 by Taught by Celeste AI - AI Coding Coach

Watch full page →

calloc and realloc — Zero-Init and Resize in C

C in 100 Seconds, Episode 21


malloc gives you raw memory with whatever garbage was left in it. calloc gives you clean memory, zeroed out. realloc lets you resize an existing block. Together, they complete the dynamic memory toolkit.

calloc: Zero-Initialized Allocation

int *nums = calloc(5, sizeof(int));

Two arguments: the count of elements and the size of each. Unlike malloc, calloc initializes every byte to zero:

for (int i = 0; i < 5; i++) {
  printf("  nums[%d] = %d\n", i, nums[i]);
}

Output:

  nums[0] = 0
  nums[1] = 0
  nums[2] = 0
  nums[3] = 0
  nums[4] = 0

With malloc, those values would be unpredictable. calloc guarantees a clean slate.

realloc: Resizing Memory

Need more space? realloc expands (or shrinks) an existing allocation:

nums = realloc(nums, 8 * sizeof(int));
nums[5] = 50;
nums[6] = 60;
nums[7] = 70;

realloc preserves the original data and extends the block to fit 8 integers. If there's room to grow in place, it does. If not, it allocates a new block, copies the data, and frees the old one — all transparently.

The Result

for (int i = 0; i < 8; i++) {
  printf("  nums[%d] = %d\n", i, nums[i]);
}

The first 5 elements (from calloc) are preserved. The new elements 5-7 hold the values you assigned.

malloc vs calloc

malloc calloc
Arguments total bytes count, element size
Initialization Uninitialized (garbage) Zeroed
Use when You'll fill it immediately You need clean defaults

Why Does This Matter?

Real programs rarely know their exact memory needs at compile time. A user might enter 5 items or 5000. calloc gives you safe starting memory, and realloc lets you grow as needed. This is how dynamic arrays, growing buffers, and resizable data structures work under the hood.

Full Code

#include <stdio.h>
#include <stdlib.h>

int main() {
  int *nums = calloc(5, sizeof(int));

  printf("calloc zeros everything:\n");
  for (int i = 0; i < 5; i++) {
    printf("  nums[%d] = %d\n", i, nums[i]);
  }

  nums = realloc(nums, 8 * sizeof(int));
  nums[5] = 50;
  nums[6] = 60;
  nums[7] = 70;

  printf("\nAfter realloc to 8:\n");
  for (int i = 0; i < 8; i++) {
    printf("  nums[%d] = %d\n", i, nums[i]);
  }

  free(nums);
  return 0;
}

Compile and Run

gcc calloc.c -o calloc
./calloc

Next episode: Memory Leaks — what happens when you forget to free.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode21