c++ - 删除后内存泄漏 []

标签 c++ pointers memory-leaks

我遇到了内存泄漏问题,我不知道是什么原因造成的。我有一个包含数组的结构。我偶尔需要调整数组的大小,所以我创建了一个新数组,其长度是旧数组的两倍,并复制所有旧值。然后我用“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)

最佳答案

您的结构不遵循 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<double>而不是使用 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 的方式.

关于c++ - 删除后内存泄漏 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311975/

相关文章:

c++ - 初始化为一个值在性能上与赋值相比如何?

javascript - jQuery.data 会导致内存泄漏吗?

c++ - 为什么长整数在某些系统上占用超过 4 个字节?

c - 棘手的指针问题

指针 vector 中的 C++ 垃圾值

c - 我的代码在第一次输入 scanf 后停止运行

ios - 使用 Xcode Instruments 从内存地址打印对象

c++ - 这种资源泄漏是由可能的评估顺序提供的还是 Scott Meyers 错了?

c++ - 图像处理基础

c++ - 模板重载在模板类中的行为不同