calloc and realloc
Zeroed and resized memory.
Beyond malloc
Besides malloc, the standard library offers calloc for zeroed memory and realloc for resizing an existing block.
Both live in <stdlib.h>.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = calloc(3, sizeof(int));
printf("%d %d %d\n", p[0], p[1], p[2]);
free(p);
return 0;
}calloc Zeroes Memory
calloc(count, size) allocates room for count elements of size bytes and sets every byte to zero.
This is convenient when you need a clean slate.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = calloc(5, sizeof(int));
int sum = 0;
for (int i = 0; i < 5; i++) sum += a[i];
printf("sum of zeroed array = %d\n", sum);
free(a);
return 0;
}All lessons in this course
- malloc and free
- calloc and realloc
- Memory Leaks
- Dangling Pointers