Allocation patterns
- C course
- Intermediate
- Lesson 11/116
- 5 min
Learn common memory allocation patterns.
malloc, calloc and realloc differences
C has three core allocation functions. malloc allocates uninitialized memory; calloc allocates zero-initialized memory; realloc resizes an existing block.
Examples: int *a = malloc(3 * sizeof(int)); may hold garbage. int *b = calloc(3, sizeof(int)); sets all elements to zero. b = realloc(b, 5 * sizeof(int)); grows the block. calloc takes two parameters (count and element size) whose product is the total size. When zero initialization is needed, prefer calloc.
The NULL check idiom
For large allocations malloc and calloc can fail; they return NULL. So a check after allocation is essential. Pattern: allocate, check, on error exit.
Example: int *arr = malloc(1000 * sizeof(int)); if (arr == NULL) return 1;. If the allocation fails the program exits with 1; otherwise it continues. In production code, on error you should also free previously allocated memory. This pattern is standard for allocations driven by user input; it's the foundation of reliable programs.
Practice Zeroed array with calloc
Allocate a three-element zeroed array with int *arr = calloc(3, sizeof(int));. Assign 5 and 7 to the first two elements. Print all three with printf("%d ", arr[i]) in a for loop; the third element should be zero thanks to calloc. End with printf("\n"). Free with free(arr);.
Starter code
#include <stdio.h>
#include <stdlib.h>
// Allocate three zeroed elements with calloc
// Assign 5 and 7 to first two
// Loop, print and free
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *arr = calloc(3, sizeof(int));
arr[0] = 5;
arr[1] = 7;
for (int i = 0; i < 3; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return 0;
}Expected output
5 7 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match function to use case
| Term | Meaning |
|---|---|
malloc(n * sizeof(T)) |
Uninitialized alloc |
calloc(n, sizeof(T)) |
Zeroed alloc |
realloc(ptr, n) |
Resize |
free(ptr) |
Release |
2 Complete the calloc call
int *arr = ____(3, sizeof(int));
int *arr = calloc(3, sizeof(int));
Explanation: calloc(count, size) allocates zeroed memory.
3 Which function zero-initializes memory?
- malloc
- calloc Correct answer
- realloc
- free
Explanation: answer: calloc. malloc doesn't initialize, calloc zeroes.