← Back to C Course | Chapter 9: Memory Management | Lesson 4 of 8

C calloc()

What is calloc()?

The zero-initialization has a real cost -- calloc() has to write zeros across the entire block, which is a small amount of extra work compared to malloc(), but it's usually worth it for the safety guarantee of starting from a known state.

Example: What is calloc()?

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *arr = calloc(3, sizeof(int));
	printf("%d %d %d", arr[0], arr[1], arr[2]);
	free(arr);
	return 0;
}

calloc() vs malloc()

In practice, calloc(n, size) is roughly equivalent to malloc(n * size) followed by memset() to zero it out, but calloc() also protects against integer overflow in that multiplication in a way manual code often doesn't.

Example: calloc() vs malloc()

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *a = malloc(3 * sizeof(int));
	int *b = calloc(3, sizeof(int));
	printf("%d", b[0]);
	free(a);
	free(b);
	return 0;
}

Allocating Arrays

This convenience is especially valuable for arrays of counters or accumulators, where starting from zero is exactly the behavior you want rather than something you'd otherwise have to set up manually in a loop after allocating.

Example: Allocating Arrays

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *counters = calloc(5, sizeof(int));
	counters[2]++;
	printf("%d", counters[2]);
	free(counters);
	return 0;
}

Allocating Structures

For a struct with pointer members, zero-initialization means those pointers start as NULL rather than garbage addresses, which makes subsequent NULL-checks meaningful before those fields have been properly assigned.

Example: Allocating Structures

c
#include <stdio.h>
#include <stdlib.h>
struct Node { int value; struct Node *next; };
int main() {
	struct Node *n = calloc(1, sizeof(struct Node));
	printf("%d", n->next == NULL);
	free(n);
	return 0;
}

Common Mistakes with calloc()

Just like with malloc(), always assign calloc()'s return value to a temporary variable first and check it before overwriting your original pointer, so you don't lose your only reference to previously allocated memory if this call fails.

Example: Common Mistakes with calloc()

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *ptr = calloc(3, sizeof(int));
	int *temp = calloc(3, sizeof(int));
	if (temp != NULL) {
		free(ptr);
		ptr = temp;
	}
	printf("%d", ptr[0]);
	free(ptr);
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.