Huny's Dev Blog
huny.dev

C Overlapping Buffer Moves: memmove, Range Checks, and Length Updates

Implement C buffer deletion with memmove and overflow-aware range checks. Includes nine boundary cases, sanitizer results, and limits around termination and data erasure.

Hun Jang
Hun Jang Nov 30, 2026

When a C TCP server removes consumed bytes from the front of a receive buffer or shifts data within one array, use memmove() if source and destination can overlap. Seeing memcpy() produce the desired result in one environment is not sufficient. This C11 example explains overlap and implements a byte-range deletion function with range checks and length updates.

A precision gripper moves a group of data tiles within the same tray, leaving a faint ghost of their previous position. A conceptual illustration of overlapping memory movement.

Written and documentation checked: 2026-11-30. Tested environment: Linux x86_64, GCC 14.2.0, C11. Only memory buffers were tested, not an actual TCP connection.

Different addresses can still overlap

For the six bytes abcdef, moving five bytes from buf to buf + 1 uses different starting addresses but shares most of the range. Linux memcpy(3) specifies that using memcpy() on overlapping regions has undefined behavior. Do not rely on copy direction or an accidentally observed output.

A simple forward byte-copy loop overwrites its own source during a right shift. In the example below, that loop produces aaaaaa. This reproduces the loop's behavior; it does not mean an invalid memcpy() always produces that result. The example does not execute an overlapping memcpy().

memmove(3) permits overlapping regions. It does not, however, enlarge the destination or calculate the correct length for you.

Define a deletion contract for the buffer

The function below removes [pos, pos + count) from len bytes of data, rather than treating the buffer as a string. It shifts the remaining len - pos - count bytes forward and reduces the logical length.

Condition
Behavior
pos is greater than len
Fail; preserve contents and length
count is greater than len - pos
Fail; preserve contents and length
count is zero at a valid position
Succeed without changes
Deletion range is valid
Move the tail and reduce length

Writing the range check as pos + count > len can overflow the addition. First establish pos <= len, then compare against the remaining range using subtraction. Short-circuit evaluation prevents the subtraction when the first condition is true.

Executable implementation and checks

Save the following as buffer_move_demo.c.

Here, memcpy() is used only to preserve an original in a distinct array. The deletion function always uses memmove(). The caller must supply valid pointers and a buffer with at least *len readable and writable bytes. The function does not discover pointer validity or actual allocation size.

Actual output follows. Assertions were not disabled with -DNDEBUG.

The checks compared two right-shift approaches and exercised nine deletion cases: front, middle, and end deletion; full deletion; zero length at the end; invalid position and length; and two SIZE_MAX inputs. Rejected requests preserved both the entire buffer and its length.

All checks also passed with the following build and execution, without AddressSanitizer or UBSan diagnostics. The environment's ptrace restriction caused the default LeakSanitizer run to fail, so execution was repeated with leak detection disabled. This does not constitute completed memory-leak verification.

These are results for the paths executed. They do not claim that a sanitizer always detects invalid memcpy() usage or prove safety across the entire input space. Other architectures, compilers, fuzzing, and performance measurements were not tested.

Logical deletion does not erase the old data

Old bytes may remain beyond the new length. This function neither clears that region nor adds a null terminator. Use the updated len when transmitting, storing, or parsing. Using the result as a C string requires separate terminator capacity and a policy such as buf[len] = '\0'. Do not simply print the buffer with %s.

Secure erasure of secrets, concurrent access by multiple threads, and reallocation while receiving are separate concerns. Repeatedly deleting small ranges can also be costly because each deletion moves the remaining bytes. A read-start index or ring buffer may be worth considering, but this article does not compare their performance. Establish overlap, range, and length contracts first, then choose a data structure after measuring the actual workload.

한국어 버전: C 겹치는 버퍼 이동은 memmove로: memcpy와 범위 검사·길이 갱신의 차이C 겹치는 버퍼 이동은 memmove로: memcpy와 범위 검사·길이 갱신의 차이

추천 글