任何人都可以帮助我,为什么我在尝试释放分配的内存时收到错误消息:检测到堆损坏。 CTR 检测到应用程序在堆缓冲区末尾之后写入了内存。
char *ff (char *s){
char *s1 = new char [strlen(s)];
strcpy(s1, s);
return s1;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *s = new char [5];
strcpy(s, "hello");
char *s2 = ff(s);
delete []s; // This works normal
delete []s2; // But I get an error on that line
return 0;
}
char *s = new char [5];
strcpy(s, "hello");
Causes 未定义行为(UB).
您的写入超出了分配的内存范围。您分配了足够的内存5
字符,但你的字符串有6
字符包括\0
.
一旦你的程序导致了这个 UB,所有的赌注都会被取消,任何行为都是可能的。
你需要:
char *s = new char [strlen("hello") + 1];
事实上理想的解决方案是使用std::string
并不是char *
。正是这些错误std::string
避免。并且没有真正需要使用char *
代替std::string
在你的例子中。
With std::string
:
- 你不需要
new
任何事物
- 你不需要
delete
任何事物 &
- 你可以做一切事情
std::string
,你做的char *
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)