Simvik

Implement memmove

Copy bytes correctly even when source and destination overlap. A medium embedded C problem (Pointers), run and graded in the browser.

medium · Pointers · libc · overlap

Implement memmove: copy n bytes from src to dst and return dst. Unlike memcpy, the regions may overlap, and the result must be as if the source had first been copied to a temporary buffer.

Do it without a temporary buffer.

Starter code

void *my_memmove(void *dst, const void *src, size_t n) {
  // Works for the non-overlapping case only.
  unsigned char *d = dst;
  const unsigned char *s = src;
  while (n--) *d++ = *s++;
  return dst;
}

Example tests

Shift down

uint8_t b[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
my_memmove(b, b + 2, 4);
printf("%u %u %u %u %u %u %u %u\n", b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);

Expected output:

3 4 5 6 5 6 7 8

Shift up

uint8_t b[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
my_memmove(b + 2, b, 4);
printf("%u %u %u %u %u %u %u %u\n", b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);

Expected output:

1 2 1 2 3 4 7 8

Learn it first

  • Pointers · Addresses, arithmetic, const, void pointers and object lifetime.

More Pointers problems