memcpy vs memmove: overlapping buffer copies in C
A receive parser often consumes part of a buffer and compacts the remaining data to its beginning. The source starts inside the same array that holds the destination. Whether an individual implementation happens to copy in a favorable direction is not a portable contract for memcpy. The C library defines memmove for overlap.
The contract
Think in ranges: a compaction copies exactly the number of unread bytes from a valid source range into a valid destination range. It then updates the logical count; bytes beyond that count do not become part of the next message. The library routine cannot infer your capacity or your parser's meaning of used length.
A small executable example
#include <string.h>
#include <assert.h>
#include <stdio.h>
int main(void) {
char buffer[] = "abcdef";
size_t used = 6, consumed = 2;
assert(consumed <= used);
memmove(buffer, buffer + consumed, used - consumed);
used -= consumed;
buffer[used] = '\0';
assert(strcmp(buffer, "cdef") == 0);
puts(buffer);
}
cdef
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
The terminating zero is written because this particular buffer represents text and has storage for it. Binary buffers need not contain a terminator. If the application instead uses fixed-size binary frames, track the remaining count without introducing a text convention. Neither memory routine performs bounds checking or makes access to concurrently modified data safe.
Checks to add in your own project
Test compaction where nothing was consumed, all data was consumed, and one byte remains. If you implement a copy routine in a freestanding environment, test both overlap directions against a trusted host implementation, using only pointers into the intended object. Check zero-length behavior against the interface contract and compare the whole destination including guard bytes. On target, measure whether avoiding frequent copies with a queue is worthwhile.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.