为什么我们需要重写终止()?

发布于 2024-12-11 06:03:53 字数 654 浏览 0 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦断已成空 2024-12-18 06:03:53

因为你正在删除你没有分配的内存。您通过“new”分配了 6 个字节,但随后将 var“mystr”重新分配给一个完全不同的指针(静态字符串“Hello”),该指针不是由“new”分配的。因此,您尝试“删除”最初不是由您分配的静态字符串“Hello”。解决方法如下:

更改这些行:

 char * mystr = new char[6]; 
 mystr = "Hello"; 

对此:

char * mystr = new char[6]; 
strcpy(mystr, "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:

 char * mystr = new char[6]; 
 mystr = "Hello"; 

To this:

char * mystr = new char[6]; 
strcpy(mystr, "Hello");

Alternatively, you could have "foo" just "return "hello";" and not delete the string in main.

热情消退 2024-12-18 06:03:53

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文