很简单的一段程序
#include <iostream.h>
#include <string.h>
void main() {
char *s = "test buffer";
int length = strlen(s);
char *testbuf = new char[length+1];
strcpy(testbuf,s);
delete []testbuf;
cout<<"delete finished"<<endl;
}
从别处看来的,起初是奇怪为什么要 new char[length+1],为什么要length+1呢,直接length不行吗?
试试...
不行,果然不行,非要length+1,不加就会弹出异常对话框。
苦恼哦,偶比较笨,刚开始以为问题出在new和delete上,也的确是执行到delete语句出错,后来愣是查了一个小时才知道原因,还不知确切不。
从MSDN查得,strlen是“Each of these functions returns the number of characters in string, excluding the terminal NULL”,也就是说字符串中有多少个字符,它就返回多少个字符的长度,并不包括结束符。
而strcpy则是“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”,即strcpy将字符串结束符也copy,并且不进行溢出检查。
所以 strcpy(testbuf.s)之后,testbuf中不仅有“test buffer”,还有结束符,长度已经不是 length,而是length+1咯。
并且由于strcpy不进行溢出检查,所以该语句并未出现异常,但当 delete []testbuf时,因为要delete的内存块大于new的内存块大小不同,所以就出现异常啦!
如果 new char[length+n] //n>=1,这样就不会出现异常,也就是说只要new 的内存大于 delete的内存,就不会出现异常。
偶是笨人,不知所述对否,哪位看到如果有错,欢迎指教,呵呵
本文通过一个简单的C++程序示例,详细解释了为什么在使用strcpy复制字符串时,需要为新分配的内存增加一个额外的空间来容纳空终止符。并通过实例演示了如果不预留这个额外空间将会导致的内存管理错误。
2095

被折叠的 条评论
为什么被折叠?



