Coding

calloc vs malloc in C: Differences and When to Use Each

The difference between calloc and malloc in C is that calloc sets every byte of the block to zero and takes two arguments (an element count and an element size), while malloc takes one byte count and leaves the memory uninitialized. Use calloc for arrays and for anything that must start zeroed, and malloc when you will overwrite the whole block before reading it.

#include <stdlib.h>

int *a = malloc(5 * sizeof *a);   /* 5 ints, contents unspecified */
int *b = calloc(5, sizeof *b);    /* 5 ints, all bytes zero */

calloc vs malloc at a glance

Propertymalloccalloc
Prototypevoid *malloc(size_t size)void *calloc(size_t num, size_t size)
ArgumentsTotal bytesElement count and element size
Initial contentsNot initializedAll bytes set to zero
Overflow in the size calculationNot detected, because you do the multiplicationReturns an error if the multiplication would overflow
Result on failureNULLNULL
How to releasefreefree

Both live in <stdlib.h>, both return a pointer suitably aligned for any object type with fundamental alignment, and both give back memory that you release with free. For the basics of allocating, freeing and finding leaks, see malloc in C: allocate, free and avoid memory leaks. This article covers only how the two functions differ.

Difference 1: calloc zeroes the memory

The Linux man page is direct about both functions. For malloc it says "The memory is not initialized". For calloc it says "The memory is set to zero". That is the difference most people mean when they search for calloc vs malloc.

With malloc, every byte holds an unspecified value until you write to it. Reading it before then is a bug, and it is an awkward one: the leftover bytes from an earlier allocation may happen to be zero on one run and not on the next, so the program looks correct in testing. With calloc you can read any element straight away and get a zero byte pattern.

Here is a case where that matters. A counter array must start at zero:

size_t counts_len = 256;
size_t *counts = calloc(counts_len, sizeof *counts);
if (counts == NULL)
    return 1;

for (size_t i = 0; i < input_len; i++)
    counts[(unsigned char)input[i]]++;

Replace calloc with malloc here and the increments start from garbage. The fix would be a memset after the malloc call, which is exactly the work calloc already does.

When malloc is the better choice: if you are about to fill the entire block yourself, for example by reading a file into a buffer with fread, zeroing first is wasted effort. Allocate with malloc, then write every byte you will later read.

Difference 2: the arguments and overflow checking

malloc takes a single size in bytes, so for an array you write the multiplication yourself: malloc(count * sizeof *items). calloc takes the count and the element size separately: calloc(count, sizeof *items).

The separate arguments matter when count comes from outside your program, such as a file header or network message. If the product of count and the element size exceeds what a size_t can hold, it wraps around to a small number. malloc then succeeds with a block much smaller than you meant, and a loop over count elements writes far past its end. The man page warns that "an integer overflow would not be detected in the following call to malloc()". For calloc it says "If the multiplication of n and size would result in integer overflow, then calloc() returns an error". In practice that means a NULL return instead of a short block.

If you stay with malloc, check the multiplication first:

if (count > SIZE_MAX / sizeof *items)
    return NULL;   /* would overflow */
struct item *items = malloc(count * sizeof *items);

SIZE_MAX comes from <stdint.h>. The cppreference page for calloc does not say what happens on overflow, so the man page is the source for this behavior. It describes the glibc implementation on Linux, and other C libraries document their own. If you target a platform whose documentation is silent, do the explicit check above rather than assuming.

What zeroed memory means for pointers and floating point

calloc sets all bits to zero. cppreference warns that this does not guarantee a floating-point value of 0.0 or a null pointer, although it is true on all common platforms. For integer types, all-bits-zero is a valid zero. For a struct containing pointers or doubles, portable code assigns those members explicitly:

struct node {
    int value;
    struct node *next;
    double weight;
};

struct node *node = calloc(1, sizeof *node);
if (node == NULL)
    return NULL;
node->next = NULL;      /* explicit, portable */
node->weight = 0.0;

Many programmers skip those two lines because every mainstream system treats zero bytes as NULL and 0.0. That is a reasonable engineering choice if you only target such systems, but it is a choice, not something the standard promises.

Is calloc slower than malloc?

Zeroing a block takes work, so a call that must write zeros can cost more than a call that writes nothing. But comparing calloc to a bare malloc is not the right comparison when you need zeroed memory. The fair comparison is calloc against malloc plus memset, and there calloc does the same job in a single call. The documentation says nothing about how fast either function is, and the answer depends on the allocator and the platform, so I am not quoting a figure. If allocation shows up in a profile of your program, measure both options with your real block sizes.

The practical rule: do not pick malloc for speed alone and then forget to initialize the memory. An uninitialized read is a far more expensive bug than a memset.

What both functions share

  • Check for NULL. Both return NULL on failure. The man page adds that these functions set errno (to ENOMEM, "Out of memory"), and notes that POSIX requires this while the C standard does not. Portable code tests the pointer, not errno.
  • Free once. A block from either function is released with free. Freeing twice, or freeing a pointer that did not come from an allocation function, is undefined behavior.
  • Zero sizes vary. The Linux man page says that with a size of 0, malloc returns a unique pointer that can be passed to free, and the same for calloc when n or size is 0. cppreference says calloc with a zero size is implementation-defined: it may return NULL or a non-NULL pointer that you must not dereference. So a NULL return from a zero-size request is not necessarily an out-of-memory error. Handle the zero case before calling.
  • The requested size may not be the actual size. cppreference notes that, because of alignment requirements, the number of bytes actually allocated is not necessarily equal to num * size. Do not rely on the extra bytes.

Which one should you use?

  • An array whose elements must start at zero: calloc. Counters, flags, hash table buckets and sparse tables are typical.
  • An array sized from untrusted input: calloc, or malloc with an explicit overflow check. calloc's built-in check is the shorter code.
  • A buffer you will overwrite completely before reading: malloc. Reading input into it or copying a string into it are the usual cases.
  • A struct you will set field by field: either works. calloc is safer if you might forget a field, because a forgotten member is zero rather than garbage.
  • A single object, no zeroing needed: malloc with sizeof *pointer.

A cheap habit that avoids most trouble: when in doubt, use calloc, then switch to malloc in the one or two places where profiling shows the zeroing matters and you are certain you overwrite the block.

Common mistakes with calloc and malloc

  • Treating malloc memory as zeroed. It is not. A string buffer from malloc is not an empty string until you write a '\0' into the first byte.
  • Swapping the arguments to calloc. calloc(sizeof *items, count) requests the same total, since the two are multiplied, so nothing fails at run time. Keep the count first and the element size second, so the call reads the same way everywhere in your code.
  • Using calloc(1, n) for a byte buffer and assuming the size is checked. With a count of 1 there is nothing to overflow, so you get zeroing but no benefit from the overflow check.
  • Passing calloc'd memory to free twice or after reassigning the pointer. The rules are the same as for malloc: free exactly once and keep a pointer to the block until you do.

Frequently asked questions

Is calloc slower than malloc?
Zeroing memory is extra work, so calloc can cost more than malloc followed by nothing. But if you would zero the block yourself with memset right after malloc, calloc does the same job in one call and may be able to skip work the allocator already knows is unnecessary. The cost depends on the allocator and the platform, so measure your own program if it matters.
Does calloc set pointers to NULL and doubles to 0.0?
Not portably. calloc sets every byte to zero. The C standard does not guarantee that an all-bits-zero pattern is a null pointer or the floating-point value 0.0, although both hold on all common platforms. Assign those members explicitly if your code must be portable.
Do I free calloc memory the same way as malloc memory?
Yes. Memory from calloc, malloc and realloc is released with free, once per block. Calling free on a block twice is undefined behavior.
What happens if calloc fails?
It returns NULL, just like malloc. On POSIX systems it also sets errno, usually to ENOMEM. The C standard does not require errno to be set, so portable code should only test the return value for NULL.

Sources