C++ComparisonsFeaturedMemoryProgramming

memcpy vs memmove in C: Differences, Overlap Behavior & Performance

4 Mins read
memcpy vs memmove in C: Differences, Overlap Behavior & Performance

Copying Memory Safely and Efficiently in C

Choosing between memcpy and memmove comes down to one important question: can the source and destination memory regions overlap? Both functions copy a specified number of bytes, but only one is defined to handle overlap. Understanding that distinction helps prevent bugs and choose the right function without relying on outdated performance assumptions.

What Do memcpy and memmove Do?

Both functions are declared in <string.h> in C and copy a specified number of bytes from a source region to a destination region. They work with memory, not specifically with strings: neither function checks for a terminating null character, and both require the caller to provide valid regions large enough for the requested copy.

The key difference is overlap. With memcpy, the source and destination regions must not overlap. With memmove, they may overlap. The C standard specifies the result of memmove as though the source bytes were first copied to a temporary, non-overlapping array and then written to the destination. An implementation does not have to create a literal temporary array; it only has to produce that result.

Function signatures

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

Here, src points to the first byte to copy, dest points to the destination, and n is the number of bytes. The standard memcpy declaration uses restrict qualifiers; the standard memmove declaration does not.

For practical guidance on using memcpy, remember to calculate the byte count carefully and ensure the destination has enough space.

memcpy vs. memmove: The Overlap Rule

Overlapping regions occur when any byte in the destination range is also part of the source range. This can happen when shifting elements within an array, removing data from a buffer, or moving a section of a character array in place.

Why overlapping memcpy is undefined behavior

The C standard makes a call to memcpy undefined if the source and destination objects overlap. The result is not guaranteed to be a particular incorrect output; the program has no defined behavior for that call. A copy may appear to work in one build and fail after a compiler change, optimization, or platform change.

For example, shifting the contents of an array one position to the right creates overlapping ranges:

#include <string.h>

int values[] = {1, 2, 3, 4, 5};

/* Undefined behavior: the ranges overlap. */
memcpy(&values[1], &values[0], 4 * sizeof values[0]);

Use memmove for this operation instead:

memmove(&values[1], &values[0], 4 * sizeof values[0]);

The result is equivalent to the original first four values being copied to a temporary array and then placed in the destination range. For more detail, see how memmove handles overlapping memory regions.

Non-overlapping copy with memcpy

When the regions are known not to overlap, memcpy is appropriate:

char source[] = "C memory";
char destination[sizeof source];

memcpy(destination, source, sizeof source);

The example copies the full array, including its null terminator. The destination is large enough, and the two arrays are distinct objects, so their ranges do not overlap.

Key Differences and Use Cases

Detail memcpy memmove
Copies bytes Yes Yes
Overlapping regions Not permitted; behavior is undefined Supported
Best fit Known non-overlapping source and destination Possibly overlapping source and destination
Null termination or bounds checking Not provided Not provided

When to use memcpy

  • Copying between separate arrays or buffers whose ranges do not overlap.
  • Copying bytes into a newly allocated destination with sufficient capacity.
  • Copying a fixed-size object representation when the objects and byte count are valid for the operation.

When to use memmove

  • Shifting elements or bytes within the same array or buffer.
  • Moving a range left or right when its source and destination may overlap.
  • Copying when overlap is possible and has not been ruled out.

If you can prove that the ranges do not overlap, memcpy is suitable. If they overlap—or you cannot safely establish that they do not—use memmove. Do not try to select a function by comparing pointer values alone unless your program’s object and range logic makes that comparison valid and meaningful.

Performance: memmove vs. memcpy

It is often said that memmove is slower because it always copies through an extra temporary array. That is not a reliable description of modern implementations. The standard specifies the result, not a particular algorithm. Libraries commonly use optimized routines that copy directly when regions do not overlap and choose a safe direction or another suitable strategy when they do.

There is no universal performance ratio. Actual speed depends on the compiler, C library, processor, copy size, alignment, and whether the regions overlap. Compilers may also recognize calls and transform them into specialized code. For small copies, call overhead and surrounding work can matter more than the choice between these functions.

How to benchmark fairly

If copying speed matters in a real application, benchmark representative workloads on the target system rather than relying on a fixed claim such as “twice as slow.” A useful test should:

  • Use realistic copy sizes, alignments, and source/destination layouts.
  • Measure both non-overlapping copies and the overlapping cases that require memmove.
  • Prevent the compiler from eliminating unused work, and repeat measurements enough to reduce timing noise.
  • Use the same compiler options and runtime environment as the application.

Correctness comes first: never replace memmove with memcpy for overlapping regions to chase a possible speed improvement. If a measured difference affects performance, optimize only after confirming the program still follows the standard’s requirements.

Common Mistakes to Avoid

  • Using memcpy on overlapping ranges: this is undefined behavior, even if it seems to work during testing.
  • Copying more bytes than the destination can hold: neither function checks buffer capacity.
  • Assuming the functions copy strings: they copy exactly n bytes and do not search for a null terminator.
  • Passing invalid or inaccessible pointers: the functions do not validate pointers or memory permissions.
  • Confusing byte counts with element counts: for arrays, multiply the element count by sizeof element, preferably using the actual object expression.

For example, sizeof values gives the size in bytes of the entire array when values is an array in that scope. By contrast, sizeof pointer gives the size of the pointer itself, not the memory block it points to.

Conclusion

The decision is simple: use memcpy when the source and destination ranges are known not to overlap, and use memmove when they may overlap. Both copy bytes, neither checks buffer sizes or null termination, and the standard does not require memmove to use a literal temporary array. Choose the correct function for the memory layout first, then benchmark if performance is a genuine concern. For a related discussion of safe concurrent access, read about thread-safe copying.

Leave a Reply

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