【问题标题】:why we need to override terminate()?为什么我们需要重写terminate()?
【发布时间】:2011-12-12 04:19:05
【问题描述】:

我的 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 ; 效果很好。

我应该释放堆上分配的内存,对吗?

但是,为什么我会出错,如果我删除它。

谢谢

【问题讨论】:

  • 在 C/C++ 中,您不能使用 '=' 运算符为 char 数组赋值,您必须使用 strcpy(或更好的 strncpy)。 C++ 还引入了 std::string 类,它可以很好地完成这项工作。

标签: c++ linux memory memory-leaks


【解决方案1】:

myString 没有在堆上分配——foo 在堆上分配了一个 char 数组,但是你扔掉指向它的指针并返回一个指向静态字符串的指针(它不在堆上)。

【讨论】:

    【解决方案2】:

    因为您正在删除未分配的内存。您通过“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 中的字符串。

    【讨论】:

    • 如果静态字符串“Hello”也分配在堆上,为什么不能删除?
    • @user: "Hello" 未在堆上分配。
    • 静态字符串和字符串有什么区别?
    • “字符串”是内存中以空字符结尾的字符序列。 “静态字符串”是静态内存中的字符串(既不在堆上,也不在堆栈上)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    相关资源
    最近更新 更多