C dynamic memory and ownership
Allocate, check, use, and free a heap buffer.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *values = malloc(3 * sizeof *values);
if (values == NULL) return 1;
for (int i = 0; i < 3; i++) values[i] = (i + 1) * 10;
printf("%d\n", values[2]);
free(values);
values = NULL;
return 0;
}30
Explanation
malloc requests a block of uninitialized memory and returns NULL if it fails. Use sizeof *pointer to size elements consistently with the pointer type.
Every successful allocation in this example has one matching free. After free, the allocation must not be read or written. Setting the local pointer to NULL helps avoid accidental reuse through that variable.
Explore the dry run
#include <stdio.h>#include <stdlib.h>int main(void) { int *values = malloc(3 * sizeof *values); if (values == NULL) return 1; for (int i = 0; i < 3; i++) values[i] = (i + 1) * 10; printf("%d\n", values[2]); free(values); values = NULL; return 0;}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Request space for three ints; the walkthrough assumes successful allocation. | values -> allocated block | — | |
| Stop with failure status if allocation failed. | values -> allocated block | — | |
| Initialize all three elements before reading. | values = [10, 20, 30] | — | |
| Read the third in-bounds element. | values = [10, 20, 30] | 30 | |
| Release the allocation. | allocation no longer valid | 30 | |
| Clear this pointer variable. | values = NULL | 30 |
Cost and common mistakes
O(n) initialization time and O(n) allocated storage for n elements; allocation cost depends on the allocator.
- Do not double-free or use memory after free.
- For a variable allocation size, check multiplication overflow before computing bytes.
Try it yourself
Allocate five ints and print the fifth initialized value.
Reveal answer and reasoning
Change both the allocation count and loop bound to 5, then print values[4], which is 50.