testing-debugging · intermediate · ~15 min
Implement defensive 2D coordinate bounds checking on flattened 1D buffers.
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.
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);
m == NULL, or rows == 0, or cols == 0, return -1.r >= rows or c >= cols, return -1 (bounds violation).safe_matrix_get, if out == NULL, return -1.r * cols + c.safe_matrix_get writes value to *out and returns 0.safe_matrix_set stores val into m[r * cols + c] and returns 0.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)
m: flattened row-major integer matrix; rows: size_t; cols: size_t; r: row index; c: col index; out/val: output pointer / input value.
Returns 0 on successful access; -1 on bounds or pointer violations.
Zero dynamic allocations. Must not read/write out of bounds.
#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;
}
Using > instead of >= for bounds checking; confusing row and column strides.
r == rows - 1 and c == cols - 1 succeeds; r >= rows fails; c >= cols fails; NULL matrix or output pointer fails.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.