pointers-memory · intermediate · ~30 min

Project: Allocate and free a dynamic 2-D array

Two-level allocation; matching free order.

Challenge

Build a dynamically allocated 2-D integer array using the "array of pointers" layout: an outer array of row pointers, each pointing to its own row of ints. Then tear it down in the matching order.

Task

Implement two functions (no main — the grader calls them):

  • int **alloc_2d(size_t rows, size_t cols) — allocate an array of rows int* pointers, each pointing to a cols-element int array. Every element starts at 0.
  • void free_2d(int **a, size_t rows) — free every row, then the outer array.

Input

rows and cols are small sizes (may be 0). free_2d receives a pointer returned by alloc_2d (or NULL) and the same rows count.

Output

alloc_2d returns the int ** (usable as a[i][j]), or NULL on allocation failure. free_2d returns nothing.

Example

int **m = alloc_2d(3, 4);
m[2][3]   ->   0          (zero-initialized)
m[1][2] = 99;             (writable; other cells stay 0)
free_2d(m, 3);

Edge cases

  • rows or cols == 0: must not crash; free_2d on the result is safe.
  • Allocation failure mid-way: free the partially built structure and return NULL.

Rules

  • Use calloc so memory is zeroed.
  • Free rows before the outer array.

Why this matters

Optional project: combine ownership, bounds, and failure handling across an API.

Input format

rows and cols are small sizes (may be 0). free_2d receives a pointer returned by alloc_2d (or NULL) and the same rows count.

Output format

alloc_2d returns the int ** (usable as a[i][j]), or NULL on allocation failure. free_2d returns nothing.

Constraints

Return NULL for zero dimensions, unrepresentable row/table sizes, or allocation failure; release every successfully allocated row on partial failure. Caller uses free_2d with the original row count; free_2d(NULL, rows) is a no-op.

Starter code

#include <stddef.h>
int **alloc_2d(size_t rows, size_t cols);
void free_2d(int **a, size_t rows);

Common mistakes

Freeing the table before its rows or forgetting partial-allocation cleanup.

Edge cases to handle

Zero dimension; one cell; non-square matrix; failure after some rows; all cells initially zero.

Complexity

O(rows * cols) to zero-init.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.