【问题标题】:C++ destructor leaks with dynamic memoryC++ 析构函数与动态内存泄漏
【发布时间】:2013-11-28 01:46:48
【问题描述】:
// Class
ArrayIntVector : IntVector{
private:
  int *data;
  int dataCapacity;
  int numElements;
  void check_invariants() const;
}

// Constructor
ArrayIntVector::ArrayIntVector(int initCapacity)
    : dataCapacity(initCapacity), numElements(0) {
    data = new int[dataCapacity];
    check_invariants();
}

// Destructor
ArrayIntVector::~ArrayIntVector() {
    check_invariants();

    delete[] data;
    data = 0;
}

int main(){

    IntVector *v = new ArrayIntVector(5);
    // testing class functions
    // push_back, pop_back, empty, index, grow
    delete v;
    return 0;
}

我正在泄漏。当我使用 valgrind 时,我得到以下信息:

堆摘要: 在退出时使用:1 个块中的 20 个字节 总堆使用量:7 次分配,7 次释放,分配 1,284 字节

1 个块中的 20 个字节肯定丢失在 1 的丢失记录 1 中 在 0x4A07152: 运算符 new[](unsigned long) (vg_replace_malloc.c:363) 通过 0x400DBE: ArrayIntVector::ArrayIntVector(int) (IntVector.cpp:12) 通过 0x401142: 主要 (lab09.cpp:8)

【问题讨论】:

  • 请提供一个完整的最小工作示例来重现该问题。否则无法判断问题出在哪里,因为我们只能猜测您在未显示的代码中做了什么。
  • 在析构函数中删除后,您不必将 data 设置为 null。当析构函数被执行时,没有更多的data
  • 您的代码是否在// do stuff 部分抛出任何异常?
  • 您正在创建一个 IntVector 类型的指针并为其分配一个 ArrayIntVector。假设它是一个子类,那么析构函数是否标记为虚拟?
  • 有人告诉我将指针设置为 null,这样您就不会意外访问刚刚删除内容的位置。它不会抛出任何异常。基类和派生类析构函数在头文件中标记为虚拟。

标签: c++ class inheritance destructor dynamic-memory-allocation


【解决方案1】:

问题是你的析构函数不是虚拟的。将析构函数声明为虚拟的。

【讨论】:

  • 在头文件中声明为virtual
  • @user2961535:你声明IntVector的析构函数是虚拟的吗?
  • 基类析构函数 IntVector 是否声明为虚拟函数?
  • 是的,所有的析构函数都在头文件中声明为virtual
  • 在头文件中 // IntVector 的析构函数(基类) virtual ~IntVector() { }; // ArrayIntVector(派生类)的析构函数 virtual ~ArrayIntVector();所有其他使用的函数都在头文件中声明,包括派生类的构造函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2023-03-25
  • 1970-01-01
  • 2021-06-13
相关资源
最近更新 更多