memcpy、memmove,memcpy和strcpy分别用
memcpy
函数原型
1 | void* memcpy(void* dest, const void* src, size_t count); |
Copies
count
bytes from the object pointed to bysrc
to the object pointed to bydest
. Both objects are reinterpreted as arrays of unsigned char.If the objects overlap, the behavior is undefined.
If either
dest
orsrc
is a null pointer, the behavior is undefined, even ifcount
is zero.If the objects are potentially-overlapping or not TriviallyCopyable, the behavior of
memcpy
is not specified and may be undefined.
如果两段内存重叠,则会导致未定义的行为;如果dest或者src是空指针(即便count=0),则是未定义的行为。
实现
1 | void *memcpy(void *dest, const void *src, size_t n) { |
测试程序
1 | void test1() { |
运行结果
1 | 1 2 3 4 5 |
比较
memcpy是最快的内存拷贝函数。它比strcpy和memmove都要快。strcpy需要扫描需要拷贝的数据,而memmove则需要检测是否存在内存重叠。
如果存在内存重叠,则应该使用memmove,而不是memcpy。
memmove
Move block of memory
Copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.
The underlying type of the objects pointed by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.
The function does not check for any terminating null character in source - it always copies exactly num bytes.
To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes.
以字节为单位,拷贝内存块。允许dest和src指向的内存块有重叠。
进行数组拷贝时,如果两段内存重叠,用memcpy函数可能会导致未定义。而memmove函数能够避免这种问题。下面是一种实现方式。题目链接
ptr1表示目的地址,ptr2表示源地址。如图所示,绿色表示数组2的元素,杏色表示数组1的元素.蓝色表示数组1和数组2重合的位置的元素。当pstr1 > pstr2时,需要逆序移动.否则,属于pstr2数组的后几个元素会被覆盖。a
当pstr1 < pstr2时,正向移动。
实现
1 | void *memmove(void *str1, const void *str2, size_t n) { |
测试程序
针对int
1 | void test1() { |
运行结果:
1 | 3 4 5 6 7 6 7 8 9 |
针对char
1 | void test3() { |
运行结果
1 | c d e f g f g h i |
strcpy
函数原型
1 | char *strcpy(char *dest, const char* src); |
Copy string
Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
strcpy只能用于拷贝C字符串(以空字符结尾)。为了防止溢出,dest指向的内存空间应该足够大,能够容纳src指向的字符串和一个表示字符串结尾的空字符。另外,dest和src指向的内存空间应该不存在重叠。
实现
1 | char *strcpy(char *dest, const char *src) { |
测试程序
1 | void test1() { |
参考文献
[1]memcpy: https://en.cppreference.com/w/cpp/string/byte/memcpy
[2]strcpy:https://www.techiedelight.com/implement-strcpy-function-c/
[3]memmove:http://www.cplusplus.com/reference/cstring/memmove/?kw=memmove
[4]memcpy等比较:https://www.cnblogs.com/youxin/p/3271074.html