malloc vs calloc in C: When to Use Uninitialized vs Zeroed Heap Memory
When using stdlib.h functionality to allocate dynamic heap memory, picking between malloc and calloc will have an impact on initialization safety and integer overflow protection. As for the difference in malloc vs calloc, malloc(size) allocates a block of garbage uninitialized memory of size bytes, while calloc(count, element_size) allocates a block of memory for count elements of element_size bytes, and also zero-initializes the allocated block. While malloc is faster in the case where you immediately overwrite the whole buffer, calloc helps to avoid problems with uninitialized-read bugs and it helps to initialize pointers or numeric arrays to zero in a clean manner.
malloc vs calloc in C: Zero Initialization & Overflow Protection — Technical Overview
When using stdlib.h functionality to allocate dynamic heap memory, picking between malloc and calloc will have an impact on initialization safety and integer overflow protection. As for the difference in malloc vs calloc, malloc(size) allocates a block of garbage uninitialized memory of size bytes, while calloc(count, element_size) allocates a block of memory for count elements of element_size bytes, and also zero-initializes the allocated block. While malloc is faster in the case where you immediately overwrite the whole buffer, calloc helps to avoid problems with uninitialized-read bugs and it helps to initialize pointers or numeric arrays to zero in a clean manner.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n = 4;
int *zeroed = calloc(n, sizeof(*zeroed));
if (zeroed != NULL) {
printf("calloc initialized: %d %d %d %d\n",
zeroed[0], zeroed[1], zeroed[2], zeroed[3]);
free(zeroed);
}
return 0;
}
Runnable C example
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n = 4;
int *zeroed = calloc(n, sizeof(*zeroed));
if (zeroed != NULL) {
printf("calloc initialized: %d %d %d %d\n",
zeroed[0], zeroed[1], zeroed[2], zeroed[3]);
free(zeroed);
}
return 0;
}Expected Output
calloc initialized: 0 0 0 0