memcpy()
和memmove()
之间的区别,并且我已经阅读了关于memcpy()
不处理重叠源和目标的文本,而memmove()
则会处理。然而,当我在重叠的内存块上执行这两个函数时,它们都给出了相同的结果。例如,参考下面MSDN帮助页面上的
memmove()
示例:-有没有更好的例子来理解
memcpy
的缺点以及memmove
是如何解决这个问题的?// crt_memcpy.c
// Illustrate overlapping copy: memmove always handles it correctly; memcpy may handle
// it correctly.
#include <memory.h>
#include <string.h>
#include <stdio.h>
char str1[7] = "aabbcc";
int main( void )
{
printf( "The string: %s\n", str1 );
memcpy( str1 + 2, str1, 4 );
printf( "New string: %s\n", str1 );
strcpy_s( str1, sizeof(str1), "aabbcc" ); // reset string
printf( "The string: %s\n", str1 );
memmove( str1 + 2, str1, 4 );
printf( "New string: %s\n", str1 );
}
输出:
memcpy():
The string: aabbcc
New string: aaaabb
memmove():
The string: aabbcc
New string: aaaabb
memcpy
会assert
(断言)这些区域没有重叠,而不是故意掩盖代码中的错误。 - R.. GitHub STOP HELPING ICE