Implement memmove
Implement void *my_memmove(void *dst, const void *src, size_t n) that copies n bytes correctly even when the source and destination regions overlap.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
If the destination starts after the source and they overlap, copying forwards overwrites source bytes before you read them. Copy backwards in that case.
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdint.h>
void *my_memmove(void *dst, const void *src, size_t n)
{
unsigned char *d = dst;
const unsigned char *s = src;
if (d == s || n == 0)
return dst;
if ((uintptr_t)d < (uintptr_t)s || (uintptr_t)d >= (uintptr_t)s + n) {
while (n--) *d++ = *s++; /* forward copy is safe */
} else {
d += n; s += n;
while (n--) *--d = *--s; /* copy backwards */
}
return dst;
}
Comparing unrelated pointers with < is technically unspecified in C, which is why the comparison is done on uintptr_t. Real library versions copy word by word once both pointers are aligned, which is much faster for large buffers.
Follow-up: why is memcpy allowed to be faster? Because its restrict parameters let it assume no overlap and copy in any order, including with SIMD or DMA.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
char a[] = "123456789";
my_memmove(a + 2, a, 5); /* overlap, dst after src */
CHECK(memcmp(a, "121234589", 9) == 0);
char b[] = "123456789";
my_memmove(b, b + 2, 5); /* overlap, dst before src */
CHECK(memcmp(b, "345676789", 9) == 0);
char c[4] = "abc", d[4] = { 0 };
CHECK(my_memmove(d, c, 4) == d && strcmp(d, "abc") == 0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}