pointers-memory · intermediate · ~25 min
Two-level allocation; matching free order.
Implement two functions:
int **alloc_2d(size_t rows, size_t cols) — returns a pointer to an array of rows int* pointers, each pointing to a cols-element int array. Zero-initialized.void free_2d(int **a, size_t rows) — frees the whole structure.True 2-D allocation in C is its own subject. Two conventions exist: 'array of pointers' (rough but flexible) and 'flat with stride math' (cache-friendly). Knowing both shapes prevents endless segfaults.
rows, cols small positive sizes.
See API.
Use calloc to zero-initialize.
#include <stddef.h>
int **alloc_2d(size_t rows, size_t cols);
void free_2d(int **a, size_t rows);
Freeing the outer array first, leaking the rows; forgetting to free a NULL-marked tail; allocating rows*cols ints in one block but accessing them as a[i][j] (only works if you actually set up the pointers).
rows or cols == 0 — must not crash. Allocation failure mid-way — clean up partial state.
O(rows * cols) to zero-init.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.