Sub topic 12
Dynamic Memory: `malloc`, `calloc`, `realloc`, and `free`
Prerequisites and the heap
Assume you know variables, functions, pointers, arrays, and basic compilation. Dynamic memory is memory requested while a program is running. It usually comes from the heap, a memory area whose lifetime is controlled by your code rather than by entering and leaving a function.
A memory-allocation function returns a pointer to a block of bytes. The pointer must be checked before use, and the block must eventually be released with free.
| Function | Purpose | Initial contents |
|---|---|---|
| `malloc(n)` | Allocates `n` bytes | Indeterminate |
| `calloc(k, s)` | Allocates space for `k` elements of `s` bytes | All bits are zero |
| `realloc(p, n)` | Resizes a previously allocated block | Preserves old contents up to the smaller size |
| `free(p)` | Releases an allocated block | The pointer must not be used afterward |
Allocating and resizing an array
Use sizeof *values instead of repeating the pointed-to type. This keeps the allocation correct if the pointer type changes.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t count = 3;
int *values = calloc(count, sizeof *values);
if (values == NULL) {
return 1;
}
values[0] = 10;
values[1] = 20;
values[2] = 30;
size_t new_count = 5;
int *temporary = realloc(values, new_count * sizeof *values);
if (temporary == NULL) {
free(values);
return 1;
}
values = temporary;
values[3] = 40;
values[4] = 50;
for (size_t i = 0; i < new_count; i++) {
printf("%d ", values[i]);
}
printf("\n");
free(values);
values = NULL;
return 0;
}realloc may move the block to a new address. Therefore, store its result in a temporary pointer. If resizing fails, the original block remains allocated and can still be freed. Assigning realloc directly to values would lose that address when the call returns NULL.
malloc leaves the bytes uninitialized. Reading an uninitialized value can produce an indeterminate result. calloc sets every bit in the allocated region to zero. This gives zero for integer objects, but portable C does not require an all-zero bit pattern to represent a null pointer or floating-point zero.
Ownership and common errors
The code that receives an allocated pointer owns the block unless ownership is deliberately transferred. It must call free exactly once.
Common errors include:
- A memory leak, where no remaining pointer can reach an allocated block.
- A dangling pointer, which points to a block after
free. - A buffer overflow caused by indexing beyond the allocated element count.
- Integer overflow in
count * sizeof *valuesbefore allocation.
Exercise
Why should realloc(values, size) usually be assigned to a temporary pointer instead of directly to values?
Show answer
If realloc fails, it returns NULL while leaving the original block allocated. A temporary pointer preserves the original address so it can be used or freed safely.