删除后的内存泄漏[]

问题描述 投票:1回答:1

我遇到内存泄漏问题,无法弄清楚是什么原因引起的。我有一个包含数组的结构。有时我需要调整数组的大小,因此我创建了一个新数组,其长度是旧数组的两倍,并复制了所有旧值。然后,我用“ 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)
c++ pointers memory-leaks
1个回答
2
投票

您的结构未跟随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的方式。

© www.soinside.com 2019 - 2024. All rights reserved.