memcpy()
is a function in the C language standard library, used to copy the contents of one memory segment to another memory segment;
memcpy Function Header File
memcpy
function's header file is <string.h>
. Before using memcpy
function, make sure to include this header file in your C code.
#include <string.h>
memcpy Function Prototype
#include <string.h>
void* memcpy(void* restrict s1,
const void* restrict s2,
size_t n);
The memcpy
function copies n
characters from the object pointed to by s2
to the object pointed to by s1
; if copying between overlapping objects, the behavior is undefined.
Parameter Description
s1
: pointer to target memory, indicating the target location of the copy;s2
: pointer to source memory, indicating the source of the data to be copied;n
: the number of bytes to be copied; when n is 0, the function will not perform any copy operation;
Return value
Returns the pointer of the target memory, that is, the value of s1
;
memcpy example code
This example demonstrates how to use the memcpy()
function to correctly copy a string;
The memcpy() function simply copies the contents of the memory byte by byte, without considering the structure and terminator of the string; so when copying a string, the length to be copied should be the length of the string + 1;
#include <stdio.h>
#include <string.h>
#include <assert.h>
int main() {
char str1[] = "hello world!";
char str2[100];
char* p;
//Copy str1 to str2
p = memcpy(str2, str1, strlen(str1) + 1);
// The pointer returned by memcpy is the same as str2
assert(p == str2);
printf("%s\n", str2);
}
Program Running Results
hello world!
Common memcpy errors
-
Source and destination memory overlap
memcpy
does not handle the situation where the source and destination memory areas overlap. If the memory areas pointed to by the source and destination pointers overlap, usingmemcpy
may result in undefined behavior. Incorrect Byte Count
When calling
memcpy
, if the number of bytes passed in (n) exceeds the size of the target memory area, it may cause a buffer overflow, resulting in memory corruption or crash.Forgetting to copy the terminator
When copying a string, you usually need to copy the terminator
\0
of the string. If you forget to add +1 inmemcpy
, the target string will not have a terminator, which may result in reading undefined memory.Using uninitialized pointers
If the source or destination pointer is uninitialized or points to an invalid memory address, calling
memcpy
will result in undefined behavior.Forget to include header file
If you forget to include the
<string.h>
header file, the compiler will not be able to recognizememcpy
, resulting in a compilation error.