Skip to content
CurriculumChapter 32 ยท Pointers & Memory
AdvancedHigh focus~16 min

calloc, realloc & Memory Bugs

calloc zeroes memory, realloc resizes it, and both can fail. Handle failure before you overwrite your only pointer.

In plain English

calloc gives you a clean box, and realloc asks for a bigger or smaller one.

01

calloc and realloc

calloc(count, size) allocates space for an array and zero-initializes it. realloc(pointer, new_size) resizes an existing block, copying the old contents when it must move. Always assign realloc to a temporary pointer first; if it fails, the original block is still valid and must not be lost.

chapter-32.cC
int *a = calloc(5, sizeof *a);   /* all zeros */
int *tmp = realloc(a, 10 * sizeof *a);
if (tmp == NULL) {
    free(a);
    return 1;
}
a = tmp;
02

Leaks, double free, and dangling pointers

A memory leak is an allocation that is never freed. A double free releases the same block twice and corrupts the allocator. A dangling pointer still holds an address after the block was freed. Set pointers to NULL after free and design ownership rules so one part of the program is clearly responsible for each allocation.

chapter-32.cC
char *p = malloc(32);
if (p) {
    strcpy(p, "owned");
    printf("%s\n", p);
    free(p);
    p = NULL;
}

Key takeaways

  • calloc zero-initializes the allocation.
  • realloc may move the block; keep the old pointer until success.
  • Free the original block if realloc fails.
  • Leaks, double frees, and dangling pointers are the classic heap bugs.

Common pitfalls

  • Overwriting the original pointer with a failed realloc result.
  • Freeing the same pointer twice.
  • Using a pointer after free.

Key focus

  • Know the difference between malloc, calloc, and realloc.
  • Expect questions on leak and dangling-pointer scenarios.

Quick check

0 / 2 answered

1. Which function allocates zero-initialized memory for an array?

2. Why should you store realloc's result in a temporary pointer?