【发布时间】:2020-04-07 09:06:01
【问题描述】:
我正在尝试重新创建向量类,并且我认为我的代码中存在内存泄漏,但我不知道如何解决它。使用我的 Visual Studio 中的 CRT 库,它告诉我,每次调用该保留时,假定的内存泄漏都会翻倍。
我不太清楚为什么会这样,或者是否存在内存泄漏。内存泄漏检测说它是保留函数中的这一行 int* temp = new int[n];
这就是我理解的储备功能中发生的事情:
一旦 arr 的内容被复制到 temp 中,删除 arr 就可以了。分配 arr = temp 应该可以工作,因为我所做的只是让 arr 指向与 temp 相同的位置。因为 arr 之前已被删除,所以我在堆中只有 1 个数组,并且 arr 和 temp 都指向同一个数组,所以应该没有内存泄漏。 Temp 无关紧要,因为它在退出范围后会消失。在随后调用 reserve 函数时,每件事都会重复,并且 arr 指向的堆中应该只有一个数组。
我确实相信我的想法在某些方面可能是错误的。
#include "Vector.h"
namespace Vector {
vector::vector() {
sz = 0;
space = 0;
arr = nullptr;
}
vector::vector(int n) {
sz = n;
space = n;
arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = 0;
}
}
void vector::push_back(int x) {
if(sz == 0) {
reserve(1);
} else if (sz == space) {
reserve(2*space);
}
arr[sz] = x;
sz++;
}
void vector::reserve(int n) {
if (n == 1) {
arr = new int[1]; //arr was a nullptr beforehand
}
int* temp = new int[n];
for(int i = 0; i < n; i++) {
temp[i] = arr[i];
}
delete[] arr;
arr = temp;
space = n;
}
【问题讨论】:
-
如果我打电话给
x.reserve(10); x.reserve(1);怎么办? -
Vector被销毁时释放内存的析构函数不会受到伤害。但是一旦你添加了,不要忘记Rule of Three。 -
当
space小于n时,请留意for(int i = 0; i < n; i++) { temp[i] = arr[i]; }。 -
想一想——如果要预留的金额小于或等于已预留的金额,您的
reserve函数将无法实现自己的目的。如果请求的金额小于当前储备金,您应该只返回。我们还需要查看minimal reproducible example,展示您如何生成此内存泄漏。我们很容易获取您的代码并破坏您的vector类,但我们需要看看您是如何破坏它的。 -
//arr was a nullptr beforehand。不,例如拨打reserve(1)两次。
标签: c++ memory-leaks