calloc and realloc
- C course
- Beginner
- Lesson 104/116
- 5 min
Learn memory management with calloc and realloc.
calloc: allocating zeroed memory
calloc also allocates memory on the heap like malloc; but it zeroes the allocated area. It comes with <stdlib.h>.
int *arr = calloc(3, sizeof(int));
// arr[0], arr[1], arr[2] are all 0It takes two arguments: the element count and the size of each element. malloc takes the total byte count in one argument, while calloc splits it into two. Zero initialization is useful for arrays and counters; it avoids surprises from garbage data.
Resizing with realloc
realloc grows or shrinks previously allocated memory. It preserves the content; if needed, it moves the data to a new location.
int *arr = malloc(2 * sizeof(int));
arr[0] = 1;
arr[1] = 2;
arr = realloc(arr, 4 * sizeof(int));
arr[2] = 3;
arr[3] = 4;Here the array starts with 2 elements; realloc makes it 4 elements. The first two are preserved, the last two are explicitly assigned. realloc may invalidate the old address; so always assign the return value back to the same pointer.
Practice Print a zeroed array with calloc
Allocate an array of 3 ints with calloc (initial values become zero). Print the three elements with printf. Finally release the memory with free.
Starter code
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* Allocate 3 ints with calloc; print elements with printf; release with free */
return 0;
}Sample solution
int *arr = calloc(3, sizeof(int));
printf("%d %d %d\n", arr[0], arr[1], arr[2]);
free(arr);Expected output
0 0 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main difference between calloc and malloc?
- calloc zeroes memory, malloc does not Correct answer
- calloc is slower
- calloc is faster
- calloc needs no free
Explanation: calloc zeroes memory; malloc leaves old data.
2 Match function to property
| Term | Meaning |
|---|---|
malloc |
Does not zero |
calloc |
Zeroes |
realloc |
Resizes |
free |
Releases |
3 Fill in the blank: calloc call
int *arr = ____(3, sizeof(int));
int *arr = calloc(3, sizeof(int));
Explanation: calloc allocates zeroed memory with two arguments.