gpt4 book ai didi

c++ - 我该如何解决此内存泄漏

转载 作者:行者123 更新时间:2023-12-02 10:07:44 26 4
gpt4 key购买 nike

我正在尝试重新创建 vector 类,我认为代码中存在内存泄漏,但是我不知道如何解决它。它在我的Visual Studio中使用CRT库,它告诉我,每次调用该保留时,内存泄漏都会增加一倍。

我不太确定为什么会这样,或者是否存在内存泄漏。内存泄漏检测说是保留函数 int * temp = new int [n];中的这一行;

我知道这是在保留功能中发生的:

将arr的内容复制到temp后,可以删除arr。分配 arr = temp 应该可以工作,因为我所做的只是将arr指向与temp相同的位置。因为arr先前已被删除,所以堆中只有1个数组,而arr和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;
}

最佳答案

您的代码在vector::reserve(int n)中假设arrnull

相反,可能会根据reserve是否为arr来说明null的工作方式。

void vector::reserve(int n) {
if (arr) { //handle case when arr is null
space += n;
arr = new int[space];
//no need to copy anything!
} else { //handle case when arr is not null
int* tmp(new int[space + n]);
for(int i = 0; i < space; i++) {
tmp[i] = arr[i];
}
delete[] arr;
arr = tmp;
space += n;
}
}

上面的代码还假设您要保留 space+n,而不是允许 reserve缩小数组,因为如果保留的空间少于先前的保留空间,则会丢失数据。通常最好的做法是在使用指针时不使用关于指针状态的假设,因为当代码变得更加复杂时,这些假设最终可能会被遗忘或变得更加晦涩难懂。

关于c++ - 我该如何解决此内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com