【问题标题】:Memory Leak after delete []删除后内存泄漏[]
【发布时间】:2019-10-09 20:40:11
【问题描述】:

我遇到了内存泄漏问题,我不知道是什么原因造成的。我有一个包含数组的结构。我偶尔需要调整数组的大小,所以我创建了一个长度是旧数组两倍的新数组,并复制所有旧值。然后我用“delete [] array”删除数组,并用新数组重新分配旧数组。

struct Structure {
    double* array = new double[1]
    int capacity = 1;
}

void resize (Structure& structure) {
    double* array = new double[structure.capacity * 2];
    for (int i = 0; i < structure.capacity; i++) {
        array[i] = structure.array[i];
    }
    delete [] structure.array;
    structure.array = array;
}

我希望旧数组被释放并替换为新数组。相反,我收到内存泄漏错误。

==91== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==91==    at 0x4C3089F: operator new[](unsigned long)

【问题讨论】:

  • 此代码无法编译。请发布正确且可以编译的代码
  • 除了你没有更新capacity之外,代码看起来还不错。你能给我们一个minimal reproducible example 导致内存泄漏触发吗?
  • 你怎么知道,这样的错误来自resize?如果您在resize 之外的任何地方都没有delete[] 内存 - 这可能是问题的原因。
  • 不相关,但你在structure.array = array 之后不做structure.capacity *= 2; 所以capacity 将留在1,即使你已经分配了2 个双打。
  • 你为什么要尝试做 std::vector 已经做的事情?此外,您没有发布 main 程序来展示您如何使用您的课程。

标签: c++ pointers memory-leaks


【解决方案1】:

您的结构没有遵循Rule of 3/5/0,特别是当结构本身被销毁时,它缺少delete[] 当前array 的析构函数:

struct Structure {
    double* array = new double[1];
    int capacity = 1;

    ~Structure() { delete[] array; } // <-- add this!

    /* also, you should add these, too:
    Structure(const Structure &)
    Structure(Structure &&)
    Structure& operator=(const Structure &)
    Structure& operator=(Structure &&)
    */
};

您确实应该使用std::vector&lt;double&gt; 而不是直接使用new[]std::vector 处理您尝试手动执行的所有操作,并且比您更安全:

#include <vector>

struct Structure {
    std::vector<double> array;

    Structure() : array(1) {}
};

void resize (Structure& structure) {
    structure.array.resize(structure.array.size() * 2);
}

或者:

#include <vector>

struct Structure {
    std::vector<double> array;

    Structure() { array.reserve(1); }
};

void resize (Structure& structure) {
    structure.array.reserve(structure.array.capacity() * 2);
}

取决于您实际使用array 的方式。

【讨论】:

    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多