calloc in C: solved exercise with zero-initialized dynamic array
calloc in C: solved exercise step by step
If you searched for a solved calloc exercise in C, here is the practical difference between calloc and malloc, and when to use each one.
calloc allocates memory for an array of n elements of size bytes each and initializes all of them to zero, unlike malloc which leaves the content undefined.
calloc signature
n— number of elements.size— size in bytes of each element.- Returns a pointer to the allocated block, or
NULLon failure.
Problem statement
- Allocate a dynamic array of 5 integers with
callocand print the initial values (all must be 0). - Fill it with the squares of 1 to 5 and print the result.
- Free the memory with
free. - Then allocate the same array with
mallocand observe that the initial values are undefined.
C solution
Expected output
malloc vs calloc vs realloc
| Function | Initializes to 0 | Resizes | Typical use |
|---|---|---|---|
malloc(n) | No | No | temporary buffer, single struct |
calloc(n, size) | Yes | No | arrays where zero is meaningful |
realloc(ptr, n) | No | Yes | arrays that grow dynamically |
Common mistakes
- Not checking if
callocreturnsNULL(out of memory). - Forgetting
free, causing a memory leak. - Assuming
mallocinitializes to zero: it never guarantees that. - Passing parameters in the wrong order: first
n(count), thensize(bytes per element).
Practical use
calloc is preferred over malloc when:
- a zero initial value is meaningful (counters, empty matrices, byte buffers),
- you want to avoid accidentally reading garbage during development.
Recommended next exercise
- Malloc and free in C: solved exercise
- malloc and realloc in C: solved exercise
- Function pointers in C: solved exercise
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
Is calloc slower than malloc?
On most systems calloc can be as fast or even faster than malloc + memset because the OS may supply already-zeroed pages. In practice the difference is negligible for small arrays.
Can I use realloc on memory allocated with calloc?
Yes. realloc works with any pointer obtained from malloc, calloc, or a previous realloc call. The new block is not zero-initialized.
When is calloc strictly required?
When code assumes array elements are zero before any write. If you always write before reading, malloc is sufficient.