testing-debugging · intermediate · ~15 min

Safe Bounded Matrix Accessor

Implement defensive 2D coordinate bounds checking on flattened 1D buffers.

Challenge

Multi-dimensional arrays flattened into 1D memory buffers are susceptible to stride miscalculations and integer wraparounds. Safe matrix accessors assert both coordinate bounds and memory strides before accessing memory.

Your Task

Implement:

int safe_matrix_get(const int *m, size_t rows, size_t cols, size_t r, size_t c, int *out);
int safe_matrix_set(int *m, size_t rows, size_t cols, size_t r, size_t c, int val);

Rules

  1. In both functions, if m == NULL, or rows == 0, or cols == 0, return -1.
  2. If r >= rows or c >= cols, return -1 (bounds violation).
  3. In safe_matrix_get, if out == NULL, return -1.
  4. Calculate index as r * cols + c.
  5. On success: safe_matrix_get writes value to *out and returns 0.
  6. On success: safe_matrix_set stores val into m[r * cols + c] and returns 0.

Example

int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
int val = 0;
safe_matrix_get((int*)grid, 2, 3, 1, 2, &val); // returns 0, val == 6
safe_matrix_get((int*)grid, 2, 3, 2, 0, &val); // returns -1 (r out of bounds)

Input format

m: flattened row-major integer matrix; rows: size_t; cols: size_t; r: row index; c: col index; out/val: output pointer / input value.

Output format

Returns 0 on successful access; -1 on bounds or pointer violations.

Constraints

Zero dynamic allocations. Must not read/write out of bounds.

Starter code

#include <stddef.h>

/* Safely read element at (r, c) from flattened rows x cols matrix. */
int safe_matrix_get(const int *m, size_t rows, size_t cols, size_t r, size_t c, int *out) {
    (void)m; (void)rows; (void)cols; (void)r; (void)c; (void)out;
    return -1;
}

/* Safely write val to element at (r, c) in flattened rows x cols matrix. */
int safe_matrix_set(int *m, size_t rows, size_t cols, size_t r, size_t c, int val) {
    (void)m; (void)rows; (void)cols; (void)r; (void)c; (void)val;
    return -1;
}

Common mistakes

Using > instead of >= for bounds checking; confusing row and column strides.

Edge cases to handle

r == rows - 1 and c == cols - 1 succeeds; r >= rows fails; c >= cols fails; NULL matrix or output pointer fails.

Background lessons

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