malloc vs calloc in C: zeroed memory and overflow checks
The commands on this page have not been executed by our verification runner yet.updated
- tool
- C
- compares
- malloc(n * size) vs calloc(n, size)
malloc(size) allocates size bytes and leaves their contents indeterminate (whatever was there before). calloc(n, size) allocates an array of n elements of size bytes each and sets every byte to zero; it also fails with NULL if n * size would overflow, while malloc(n * size) silently allocates a wrong, smaller size when the multiplication overflows. Use calloc when you need zeroed memory or are allocating an array from a count; use malloc when you will overwrite every byte anyway.
Differences
| malloc | calloc | |
|---|---|---|
| Signature | void *malloc(size_t size) | void *calloc(size_t nmemb, size_t size) |
| Contents | Indeterminate (not initialized) | All bits zero |
| n * size overflow | Your multiplication wraps around: too small a buffer | Detected: returns NULL |
| Cost | Allocation only | Allocation plus zeroing (often free for fresh pages from the OS) |
| Failure | Returns NULL | Returns NULL |
| Release | free() | free() |
Example
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n = 1000;
int *a = malloc(n * sizeof *a); /* contents undefined until written */
int *b = calloc(n, sizeof *b); /* every element is 0 */
if (a == NULL || b == NULL) {
perror("alloc");
free(a); free(b);
return 1;
}
for (size_t i = 0; i < n; i++) a[i] = (int)i; /* malloc: initialize before reading */
printf("%d %d\n", a[999], b[999]); /* 999 0 */
free(a);
free(b);
return 0;
}Notes
- All bits zero is
0for integers and, on every common platform,0.0for IEEE 754 floating point andNULLfor pointers, but the C standard does not guarantee the last two. - Reading memory from
mallocbefore writing it is undefined behaviour; tools such as Valgrind (Conditional jump or move depends on uninitialised value) and MemorySanitizer report it. - To grow a buffer use
realloc; newly added bytes are not zeroed. glibc also providesreallocarray(ptr, n, size)with the same overflow check ascalloc. sizeof *ptrinstead ofsizeof(int)keeps the size correct if the pointer type changes.
Sources
Related pages
errors · cSegmentation fault (core dumped) in a C programA segfault means the program touched invalid memory: a NULL or dangling pointer or an out-of-bounds index. Find the line with -fsanitize=address or with gdb.errors · cC error: implicit declaration of function 'foo' [-Wimplicit-function-declaration]C compilers reject a call to a function with no prior declaration; GCC 14 and Clang 16 made it an error. Include the right header or add a prototype first.flags · cgcc -Wall -Wextra -Werror: enable compiler warningsgcc -Wall -Wextra enables the warnings that catch most C bugs: unused variables, format mismatches, signed comparisons. -Werror makes warnings fail the build.