Handling overlapping regions with memmove
What you'll learn: How to safely shift data within a single array without corrupting your information.
The problem with memcpy
Imagine you have a row of books on a shelf and you want to slide them two inches to the right. If you use memcpy, it acts like a robot that picks up one book and places it in its new spot, then goes back for the next.
If the destination overlaps with the original spot, the robot might overwrite "Book 3" before it has a chance to move it. By the time it reaches the original spot for Book 3, it finds a duplicate of Book 1 instead. The original data is gone forever. This is known as "undefined behavior."
The memmove solution
Despite its name, memmove doesn't actually "move" data in the sense of deleting the source; it copies it. However, it is designed to be "overlap-aware."
In our bookshelf analogy, memmove is smarter. It looks at the destination and says, "If I move from left-to-right, I'll overwrite my data. I should start from the back and move right-to-left instead." It ensures the integrity of the data regardless of where the source and destination sit in memory.
How to use it
The syntax is identical to memcpy. You provide the destination, the source, and the number of bytes to copy.
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "Hello World";
// Goal: Shift "World" to start one index earlier
// Source: text + 6 ("World")
// Destination: text + 5 (where the space is)
// Result should be "HelloWorld"
memmove(text + 5, text + 6, 6);
printf("%s", text); // Output: HelloWorld
return 0;
}
When to use which?
You might wonder why we don't use memmove for everything. The answer is performance. Because memmove has to check for overlaps and potentially copy data in reverse, it can be slightly slower than the "dumb" memcpy.
Use memcpy when you are 100% sure the two memory blocks are distinct (like copying from one array to a completely different one). Use memmove whenever you are shifting data around within the same array.
Key takeaway
Use memmove instead of memcpy when the source and destination memory regions overlap to prevent data corruption.