Simvik

Fix: copying a block corrupts the next variable

A copy loop runs one element past the end of both arrays. An easy embedded C problem (Arrays and strings), run and graded in the browser.

easy · Arrays and strings · find-the-bug · off-by-one · arrays

Bug report. copy_samples(dst, src, n) copies n samples. Since it was added, the variable stored after the destination buffer changes whenever a block is copied. Fix it by changing one line.

Starter code

void copy_samples(int16_t *dst, const int16_t *src, int n) {
  for (int i = 0; i <= n; i++) dst[i] = src[i];
}

Example tests

Copy four samples

int16_t src[4] = { 1, -2, 3, -4 }, dst[4];
copy_samples(dst, src, 4);
printf("%d %d %d %d\n", dst[0], dst[1], dst[2], dst[3]);

Expected output:

1 -2 3 -4

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems