
Using memmove for Safe C String Manipulation
When you edit a string in C, the source and destination regions may overlap. That is where memmove becomes especially useful: it copies a specified number of bytes while preserving the original data even when those regions overlap. This guide explains how to use memmove for common string operations, with practical examples and the checks needed to keep them safe.
What Does memmove Do?
memmove, declared in <string.h>, copies n bytes from a source region to a destination region and returns the destination pointer. Its standard C signature is:
void *memmove(void *dest, const void *src, size_t n);
Unlike strcpy, memmove works with a specified byte count and does not stop at a null character. Unlike memcpy, it is defined for overlapping source and destination regions. The implementation behaves as though the source bytes are first copied to a temporary, non-overlapping array, although a library implementation need not actually allocate such an array.
That overlap guarantee makes memmove a useful tool for shifting parts of a string buffer. For broader context, see Cross-Platform Behavior of memmove.
C Strings, Buffers, and Byte Counts
A C string is a sequence of characters ending with the null character, '\0'. The null terminator is not optional: functions that expect a C string need to encounter it within the available buffer. Because memmove copies bytes rather than interpreting strings, you must calculate the byte count and include the terminator whenever it needs to move.
Before modifying a string, confirm that the destination buffer is large enough. Also ensure the source and destination point to valid regions containing at least the requested number of bytes. memmove handles overlap, but it does not check buffer capacity, validate pointers, or prevent out-of-bounds access.
Using memmove for String Manipulation
For in-place edits, a common pattern is to find the position where a change begins, then shift the suffix of the string. The suffix count should generally include the terminating null character so the result remains a valid C string.
Removing a Substring
This example removes count characters beginning at pos. It shifts the remaining suffix, including '\0', to the left:
#include <string.h>
#include <stddef.h>
int remove_range(char *s, size_t capacity, size_t pos, size_t count)
{
size_t len = strlen(s);
if (pos > len || count > len - pos)
return 0;
/* The buffer must contain the string and its terminator. */
if (len >= capacity)
return 0;
memmove(s + pos, s + pos + count, len - pos - count + 1);
return 1;
}
For example, removing three characters from "abcdef" at position 2 produces "abf". The source and destination ranges overlap, so memmove is appropriate. The checks also avoid invalid positions and ensure the terminator moves with the suffix.
Inserting Text into a String
To insert text, first shift the existing suffix—including the terminator—to the right. Then copy the inserted text into the newly opened space. The following example assumes the source text is separate from the destination buffer:
#include <string.h>
#include <stddef.h>
int insert_text(char *s, size_t capacity, size_t pos, const char *text)
{
size_t len = strlen(s);
size_t add = strlen(text);
if (pos > len || len >= capacity || add > capacity - len - 1)
return 0;
memmove(s + pos + add, s + pos, len - pos + 1);
memcpy(s + pos, text, add);
return 1;
}
The capacity test reserves one byte for the final null terminator. Here, memmove shifts the existing suffix safely; memcpy is used for the new text because the example requires text to be separate and non-overlapping. If the insertion source might overlap the destination buffer, handle that case explicitly—for example, by saving the insertion text before shifting.
Choosing Between memmove and Other C Memory Functions
Use the function that matches the data and overlap conditions:
memmovecopies a known number of bytes and supports overlap.memcpycopies a known number of bytes, but source and destination regions must not overlap.strcpycopies a null-terminated string, but the destination must have enough space and the regions must not overlap.memsetfills a region with a repeated byte; it does not copy another region.
Choosing memmove does not automatically make an operation safe. Correct bounds, valid pointers, and accurate byte counts still matter. In systems with timing constraints, assess the operation’s worst-case cost as part of the overall design; see memmove in Real-Time Applications. For compute-heavy workloads, the memory movement and access patterns may also be relevant to memmove in High-Performance Computing.
Common Mistakes to Avoid
- Forgetting the null terminator: When shifting the end of a string, include the terminator in the byte count.
- Assuming capacity is checked:
memmovereceives no buffer-size information, so validate space yourself. - Confusing bytes with characters: In UTF-8 text, a character may occupy multiple bytes. Moving bytes is safe only when the chosen boundaries preserve valid encoding.
- Using
memcpyfor overlapping ranges: Usememmovewhen overlap is possible. - Passing an incorrect count: A count that exceeds either valid region can cause undefined behavior.
Conclusion
memmove is a practical C memory function for editing strings in place, especially when shifting overlapping portions of a buffer. Use it to move the suffix when removing or inserting text, and include the null terminator whenever the moved region must remain a valid C string. Just as importantly, check positions, lengths, and buffer capacity before every operation. With those habits, you can use memmove confidently while keeping string manipulation clear, portable, and within bounds.