现在的位置: 首页 > 综合 > 正文

关于strcpy函数

2013年02月19日 ⁄ 综合 ⁄ 共 587字 ⁄ 字号 评论关闭

先看一个例子:

char* GetMemory(int num)

{

    return new char[num]; 

}


int main()

{

char* str = GetMemory(10);

char tmp[10];


/*

 虽然str和tmp的空间大小都为10,但是:

 The strcpy function copies strSource, including the terminating null character, 

 to the location specified by strDestination. No overflow checking is performed 

 when strings are copied or appended. The behavior of strcpy is undefined if the 

 source and destination strings overlap.

*/


strcpy(str, "12345678900000");


strcpy(tmp, "0123456789");


cout<<str<<endl;


cout<<tmp<<endl;


return 0;

}



无论strcpy的第一个参数是char*还是char数组,在字符串被拷贝的时候(或者添加的时候strcat)都不执行上溢出检测!

如果源和目的字符串重叠,则这个函数的行为是未定义的。


由于strcpy不检查空间的完备性,因而可能造成缓冲区越界。

抱歉!评论已关闭.