学写库函数memmove
终于决定整理自己的写的库函数了
#include <stdio.h>
void *ystd_memmove(const void *src,void *dst,size_t n)
{
void * ret = dst;
//not overlap
if((dst < src)||(src + n)<= dst)
{
while(n--)
*(char *)dst++ = *(char *)src++;
}else if(src < dst){//if src == dst quickly return
dst += n;
src += n;
while(n--)
*(char *)(--dst) = *(char *)(--src);
}
return ret;
}
int main()
{
char buf[]= "hunter you can't do it";
char mem[100] ;
//内存区域不重合
ystd_memmove(buf,mem,sizeof(buf));
printf("mem = %s\n",mem);
//内存区域重合了
ystd_memmove(mem,mem+10,sizeof(buf));
printf("mem = %s\n",mem);
return 0;
}
测试结果
mem = hunter you can't do it
mem = hunter youhunter you can't do it
其实代码再添加写assert判断,就好了。呵呵,大家做个参考吧。