Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

memmove — C23 overlap-safe byte copy

`memmove(s1, s2, n)` from `<string.h>` copies `n` bytes of representation from source to writable destination and returns the original `s1`. Unlike `memcpy`, its result is defined when the ranges overlap: semantics are as if the source bytes were first copied into a separate temporary array of `n` bytes.

Version: C23

Syntax

void *memmove(void *s1, const void *s2, size_t n);

memmove(s1, s2, n) from <string.h> copies n bytes of representation from source to writable destination and returns the original s1. Unlike memcpy, its result is defined when the ranges overlap: semantics are as if the source bytes were first copied into a separate temporary array of n bytes.

The example shifts the first four bytes of "ABCDE" one position to the right within the same buffer. The ranges deliberately overlap, and output 1 AABCD confirms both the returned text + 1 pointer and preservation of the original bytes despite forward overwriting.

Overlap safety does not repair bad bounds: both n-byte ranges must fit accessible objects, the destination must be writable, and pointer values remain required even for n == 0. The function copies bytes, not elements or resource ownership, and it does not add a \0; when moving part of a string, include the terminator explicitly if it belongs in the result.

Examples

#include <stdio.h>
#include <string.h>
int main(void){char text[]="ABCDE";void *result=memmove(text+1,text,4);printf("%d %s\n",result==text+1,text);return 0;}

Result

1 AABCD

The example shifts the first four bytes of `"ABCDE"` one position to the right within the same buffer. The ranges deliberately overlap, and output `1 AABCD` confirms both the returned `text + 1` pointer and preservation of the original bytes despite forward overwriting.

Sources