#include<iostream>
#include<assert.h>
using namespace std;
//此版本并未考虑到内存重叠的情况
char* strcpy_overwrite1(char*Des,char*Src)
{
assert(Des!=NULL);
assert(Src!=NULL);
//assert的作用是现计算表达式 expression
//如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
char *Res=Des;
while ((*Des++=*Src++)!='\0');
return Res;
}
void * memcpy_overwrite(void *dst,const void *src,unsigned int count)
{
assert(dst!=NULL);
assert(src!=NULL);
char*pdst;
char*psrc;
if (dst>src&&dst<((char*)src+count))//内存如果重叠冲后往前赋值
{
pdst=(char*)dst+count-1;//内型的转换
psrc=(char*)src+count-1;
while (count--)
{
*pdst--=*psrc--;
}
}
else
{
pdst=(char*)dst;//不重叠的
psrc=(char*)src;
while(count--)
{
*pdst++=*psrc++;
}
}
return dst;
}
char* strcpy_overwrite2(char*Des,char*Src)
{
assert(Des!=NULL);
assert(Src!=NULL);
//assert的作用是现计算表达式 expression
//如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
//memcpy(Des,Src,strlen(Src)+1);
memcpy_overwrite(Des,Src,strlen(Src));
return Des;
}
int main()
{
char str[10]="123";
//strcpy_overwrite1(str+1,str);//出错
//strcpy(str+1,str);
strcpy_overwrite2(str+1,str);
cout<<str<<endl;
return 0;
}
strcpy与memcpy重新实现
最新推荐文章于 2023-03-02 19:17:58 发布