删除[]

时间:2019-10-09 20:40:11

标签: 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)

1 个答案:

答案 0 :(得分:3)

您的结构未遵循Rule of 3/5/0,特别是当结构本身被销毁时,它缺少对当前delete[]的{​​{1}}的析构函数:

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); } 的方式。