Lesson 22 of 31

Calloc and Realloc

Calloc and Realloc

Beyond malloc, C provides two more functions for managing heap memory.

calloc

calloc(count, size) allocates memory for count elements of size bytes each, and initializes all bytes to zero:

// Allocate 10 ints, all initialized to 0
int *arr = (int *)calloc(10, sizeof(int));
printf("%d\n", arr[0]);  // 0 (guaranteed)
free(arr);

Compare with malloc, which leaves memory uninitialized:

FunctionSyntaxZeroed?
mallocmalloc(size)No
calloccalloc(count, size)Yes

Expanding the Enterprise: realloc is like adding a new deck to the ship while everyone's still aboard.

realloc

realloc(ptr, new_size) resizes a previously allocated block. It may move the data to a new location:

int *arr = (int *)malloc(3 * sizeof(int));
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;

// Grow to 5 elements
arr = (int *)realloc(arr, 5 * sizeof(int));
arr[3] = 40;
arr[4] = 50;
free(arr);

Key Rules

  • realloc preserves existing data up to the minimum of old and new sizes
  • realloc(NULL, size) behaves like malloc(size)
  • Always assign the result of realloc -- the pointer may change

Common Pitfall: Losing the Original Pointer

Never assign realloc directly to the same pointer without checking for failure:

// DANGEROUS: if realloc fails, arr is lost (memory leak)
arr = (int *)realloc(arr, new_size);

// SAFER: use a temporary pointer
int *tmp = (int *)realloc(arr, new_size);
if (tmp != NULL) {
    arr = tmp;
}

If realloc returns NULL, the original block is still valid. Overwriting the pointer with NULL means you can never free the original block.

Your Task

Write a function int *zeros(int n) that uses calloc to allocate an array of n integers (all zero). Write a function int *grow(int *arr, int old_n, int new_n, int fill) that uses realloc to grow the array and fills new slots with fill. Print all elements after growing.

TCC compiler loading...
Loading...
Click "Run" to execute your code.