下面是我的测试代码:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[]="abcdefghigklmnopqrstuvwxyz abcdefghigklmnopqrstuvwxyz";
memmove(s,s+7,strlen(s)+1-7);
printf("Memmove result forward : %s\n",s);
char s1[]="abcdefghigklmnopqrstuvwxyz abcdefghigklmnopqrstuvwxyz";
memcpy(s1,s1+7,strlen(s1)+1-7);
printf("Memcpy result forward : %s\n",s1);
char s2[]="abcdefghigklmnopqrstuvwxyz abcdefghigklmnopqrstuvwxyz";
memmove(s2+7,s2,strlen(s2)+1-7);
printf("Memmove result afterward: %s\n",s2);
char s3[]="abcdefghigklmnopqrstuvwxyz abcdefghigklmnopqrstuvwxyz";
memcpy(s3+7,s3,strlen(s3)+1-7);
printf("Memcpy result afterward : %s\n",s3);
getchar();
return 0;
}
运行的结果为:
Memmove result forward : higklmnopqrstuvwxyz abcdefghigklmnopqrstuvwxyz
Memcpy result forward : higklmnopqrstuvcdlmnopqrsmnopqrsmnopqrstuvwxyz
Memmove result afterward: abcdefgabcdefghigklmnopqrstuvwxyz abcdefghigklmnopqrst
Memcpy result afterward : abcdefgabcdefghigklmnoigklmnopgklmnopxefghigklmnopqrst
你应该用memmove API,它可以避免重叠的问题
我知道用memmove啊,我只是想知道为什么memcpy前向后向都有问题,memcpy的源函数看前向应该没有问题啊,是在优化的时候出的问题吗?