memmove
is a function in the C language standard library that copies a specified number of bytes from a source memory block to a target memory block. Unlike memcpy, memmove
can safely handle memory overlap situations to avoid data corruption.
memmove Function Header File
memmove
function's header file is <string.h>
. Before using memmove
function, make sure to include this header file in your C code:
#include <string.h>
memmove Function Prototype
void *memmove(void *s1,
const void *s2,
size_t n);
memmove
function copies n
characters from the object pointed to by s2
to the object pointed to by s1
.
The copying process is as follows:
- First, copy the
n
characters in the object pointed to bys2
to a temporary array ofn
characters that does not overlap with the objects pointed to bys1
ands2
; - Then copy the
n
characters in the temporary array to the object pointed to bys1
.
Parameter Description
s1
: Pointer to the target memory, indicating the target location of the copy;s2
: Pointer to the source memory, indicating the source of the data to be copied;n
: The number of bytes to be copied;
Return value
memmove
function returns the pointer of the target memory block, which is the value of s1
.
memmove example code
The following is a simple example showing the use of the memmove
function in the case of overlapping memory:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
// The source address memory and the target address memory overlap
// Use memmove to handle safely
memmove(str, str + 7, 5);
str[5] = '\0'; // Add a null character to the end of the string
printf("%s\n", str);
return 0;
}
Program Running Results
World