为什么我们需要重写终止()?
我的 C++ 程序有一个错误:
#include<iostream>
using namespace std;
char* foo()
{
char * mystr = new char[6];
mystr = "Hello";
return mystr ;
}
int main()
{
char* myString =foo();
printf("%s \n", myString);
delete [] myString ;
}
==27472== Invalid free() / delete / delete[]
==27472== at 0x4A07A12: operator delete[](void*) (vg_replace_malloc.c:409)
==27472== by 0x4007EB: main (printHello.cpp:16)
==27472== Address 0x4008f8 is not stack'd, malloc'd or (recently) free'd
如果我删除 delete [] myString ;
它工作正常。
我应该释放堆上分配的内存,对吗?
但是,为什么我删除它会出错。
谢谢
My C++ program has an error:
#include<iostream>
using namespace std;
char* foo()
{
char * mystr = new char[6];
mystr = "Hello";
return mystr ;
}
int main()
{
char* myString =foo();
printf("%s \n", myString);
delete [] myString ;
}
==27472== Invalid free() / delete / delete[]
==27472== at 0x4A07A12: operator delete[](void*) (vg_replace_malloc.c:409)
==27472== by 0x4007EB: main (printHello.cpp:16)
==27472== Address 0x4008f8 is not stack'd, malloc'd or (recently) free'd
If I remove delete [] myString ;
it works well.
I should free the memory allocated on heap, right ?
But, why I got error, if I delete it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你正在删除你没有分配的内存。您通过“new”分配了 6 个字节,但随后将 var“mystr”重新分配给一个完全不同的指针(静态字符串“Hello”),该指针不是由“new”分配的。因此,您尝试“删除”最初不是由您分配的静态字符串“Hello”。解决方法如下:
更改这些行:
对此:
或者,您可以让“foo”只是“return“hello”;”,而不删除 main 中的字符串。
Because you are deleting memory you didn't allocate. You allocate 6 bytes via "new", but then you reassign the var "mystr" to a completely different pointer (static string "Hello") that wasn't allocated by "new". So you attempt to "delete" the static string "Hello" that wasn't allocated by you in the first place. Here's the fix:
Change these lines:
To this:
Alternatively, you could have "foo" just "return "hello";" and not delete the string in main.
myString
未在堆上分配 -foo
在堆上分配一个 char 数组,但随后丢弃指向它的指针并返回指向静态字符串的指针(不在堆上)。myString
wasn't allocated on the heap --foo
allocates a char array on the heap, but then you throw away the pointer to it and return a pointer to a static string (which is not on the heap).