C++FeaturedMemoryProgrammingTutorials

Write Your Own memmove in C: Implementation Tutorial & Edge Cases

5 Mins read
Write Your Own memmove in C: Implementation Tutorial & Edge Cases
Custom Memmove Implementation Tutorial in C

How to Implement memmove Safely in C

Copying bytes in C is straightforward until the source and destination ranges overlap. In that case, a forward copy can overwrite bytes that have not yet been read. The standard memmove function handles this situation by selecting a safe copy direction. This guide explains the overlap logic, presents a compact memmove implementation in C, and shows how to test it against the C library.

If you are deciding between the two standard copy functions, see memcpy vs memmove. The key difference is that memcpy requires non-overlapping regions, while memmove supports overlap.

What memmove Guarantees

The C standard declares memmove in <string.h> with this prototype:

void *memmove(void *dest, const void *src, size_t n);

It copies up to n bytes from the source object to the destination object and returns the original destination pointer. Its behavior is specified as if the source bytes were first copied into a temporary, non-overlapping array and then written to the destination. An implementation does not have to allocate such an array; it only has to produce the same result.

Both ranges must refer to valid memory for the requested number of bytes. If n is zero, the function performs no byte accesses. As with other standard-library operations, passing invalid pointers or requesting a range that extends beyond the accessible objects is not made safe by choosing memmove.

Why Copy Direction Matters

For non-overlapping ranges, copying from low addresses to high addresses is safe. For overlapping ranges, the correct direction depends on their relative positions. This is the central idea behind a memmove implementation.

Suppose the destination begins inside the source range at a higher address. A forward copy could replace a source byte before it has been read, so copy backward from the end. If the destination is below the source, copying forward is safe: writing a lower byte cannot destroy a later source byte. The same forward approach works when the ranges do not overlap.

For a visual explanation of this decision, read how memmove handles overlapping memory.

A Simple Direction-Aware memmove Implementation in C

The following educational implementation uses byte-wise copying and does not allocate a temporary buffer. It assumes that the requested source and destination ranges are valid. The integer-address comparison is a practical technique on common flat-address systems, but strict ISO C does not generally define relational comparison of pointers to unrelated objects or guarantee that converting pointers to integers provides a portable ordering. For production code, prefer the platform’s C library unless your target environment documents the required address model.

#include <stddef.h>
#include <stdint.h>

void *custom_memmove(void *dest, const void *src, size_t n)
{
    unsigned char *d = (unsigned char *)dest;
    const unsigned char *s = (const unsigned char *)src;

    if (n == 0 || d == s) {
        return dest;
    }

    /*
     * This address-order test assumes uintptr_t reflects the
     * target platform's ordinary memory-address ordering.
     */
    if ((uintptr_t)d < (uintptr_t)s ||
        (uintptr_t)d - (uintptr_t)s >= n) {
        for (size_t i = 0; i < n; ++i) {
            d[i] = s[i];
        }
    } else {
        for (size_t i = n; i != 0; --i) {
            d[i - 1] = s[i - 1];
        }
    }

    return dest;
}

How the algorithm works

  • Zero bytes or identical pointers: no copy is necessary, so the original destination pointer is returned.
  • Destination below source: copy forward, because writes cannot overwrite source bytes that are still needed.
  • Destination at or beyond the source range: copy forward; the ranges do not overlap in the dangerous direction.
  • Destination inside the source range at a higher address: copy backward to preserve unread source bytes.

The subtraction in the address test is performed only after confirming that the destination address is not lower. This avoids computing source + n, which could overflow an integer address or form a pointer beyond its valid range. However, the address-order assumption remains platform-specific, so this example is best treated as a learning exercise rather than a universally portable replacement.

Forward and Backward Copy in Practice

Consider a byte array containing ABCDEFGHIJ. Moving seven bytes from offset 0 to offset 2 creates an overlapping destination that starts inside the source. A forward loop would write over source bytes before reading them; a backward loop preserves the original sequence. Moving from offset 2 to offset 0 is safe in the forward direction because each source byte is read before a lower destination byte is written.

This is why simply writing a loop from index zero to n - 1 is not enough. A correct custom implementation must account for overlap, not merely copy each byte once.

Why Avoid a Temporary Allocation?

A temporary buffer can make overlap handling intuitive: copy the source into the buffer, then copy the buffer to the destination. But allocating memory for every call is usually inefficient and introduces failure handling. The standard function does not promise to allocate a temporary array; implementations commonly choose a direction or use more advanced techniques while preserving the specified result.

A custom routine should also avoid assuming that a wider-word copy is automatically faster. Alignment, architecture, compiler optimization, and overlap all affect performance. Handwritten byte loops are useful for understanding the algorithm, but they are not necessarily faster than the system library.

Testing a Custom memmove

Tests should cover both the required behavior and the boundary cases. Use separate arrays for non-overlapping copies and one array for overlapping moves. Compare the entire resulting buffer, not just the copied destination bytes, so accidental writes outside the destination are detected.

  • Copy zero bytes and verify that the destination remains unchanged and the return value equals dest.
  • Copy one byte and copy a range that ends at the last valid byte of an array.
  • Test non-overlapping source and destination ranges in both address orders.
  • Test overlap with the destination above the source, then overlap with the destination below the source.
  • Test identical source and destination pointers.
  • Use varied byte patterns, including zero bytes and values above 0x7f.

For reliable expected results, initialize a separate reference buffer and use the platform’s memmove to produce the expected output. Then run the custom function on an identical copy and compare the full arrays with memcmp. Keep the reference and custom destination buffers separate so the test itself does not introduce overlapping operations or overwrite its expected result.

More test ideas and edge cases are covered in unit test memmove.

Comparing with the C Library

For everyday C development, use the standard memmove from <string.h>. Mature libraries may select optimized routines for the processor, size, and alignment, and compilers may recognize standard calls and optimize them. Exact implementation details vary by compiler, C library, target architecture, and build settings.

Do not assume that a library always copies forward for one case and backward for another in a particular way, or that every implementation uses the same instructions. The guarantee is the result, not a specific internal algorithm. Likewise, avoid benchmarking a custom routine without controlling for compiler optimization, input sizes, alignment, cache state, and whether the call was inlined or replaced by a compiler intrinsic.

When a Custom Implementation Makes Sense

A small custom routine can be useful for learning, embedded environments with unusual constraints, or code that must work before a standard library is available. It may also help when investigating memory behavior or building a focused test harness.

For general application code, a handwritten replacement adds portability and correctness risks without a clear benefit. Use the standard function unless measurements and documented platform requirements justify a specialized alternative. Never use memcpy as a substitute when the ranges might overlap; its overlap behavior is undefined.

Conclusion

A correct memmove implementation preserves the source data when ranges overlap by choosing a safe copy direction: forward when the destination is lower or the ranges are safely separated, and backward when the destination begins inside the source at a higher address. That simple rule explains the core behavior, but portable pointer-order reasoning and performance tuning require care. Study the algorithm, test overlap and boundary cases against the library function, and rely on the standard memmove for production code unless a specialized implementation is demonstrably necessary.

Leave a Reply

Your email address will not be published. Required fields are marked *