Simvik

Implement memcpy

Copy a block of bytes between two non-overlapping buffers. A medium embedded C problem (Pointers), run and graded in the browser.

medium · Pointers · libc · void-pointer

Implement memcpy: copy n bytes from src to dst and return dst. The two regions do not overlap.

Starter code

void *my_memcpy(void *dst, const void *src, size_t n) {
  // Copy n bytes from src to dst and return dst.
  return dst;
}

Example tests

Copy into the middle of a buffer

uint8_t src[4] = { 1, 2, 3, 4 }, dst[6] = { 9, 9, 9, 9, 9, 9 };
my_memcpy(dst + 1, src, 4);
printf("%u %u %u %u %u %u\n", dst[0], dst[1], dst[2], dst[3], dst[4], dst[5]);

Expected output:

9 1 2 3 4 9

Copy an object of another type

uint32_t a = 0xDEADBEEF, b = 0;
my_memcpy(&b, &a, sizeof a);
printf("0x%08X\n", b);

Expected output:

0xDEADBEEF

Learn it first

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

More Pointers problems