调整C++动态数组大小时出现C++内存泄漏错误

yzuktlbb  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(175)

下面的代码通过将9转换为最大可能部分的总和,将数组3,9,3转换为整数3,3,3,3,3的排序数组。
此代码中使用的代码/算法的链接可在以下位置找到
https://stackoverflow.com/a/75331557/21145472
我被这段C++代码震惊了。昨天运行它的时候还不错,但是今天当函数resizeArray()第三次运行的时候,它给出了内存泄漏错误。
请帮助修复此内存泄漏

#include<cmath>
#include <algorithm>
#include <iterator>
using namespace std;

void resizeArray(int *orig, int size, int newSize) {
        int *resized = new int[newSize];
        for (int i = 0; i < size; i ++)
            resized[i] = orig[i];
        delete [] orig;
        orig = resized;
}

int main(){
    int n = 3;
    int *arr = new int[n];
    int arrLength = n;
    arr[0] = 3;
    arr[1] = 9;
    arr[2] = 3;
    int *arrSorted = new int[0];
    int sortedArrayLength = 0;
    int temp;
    unsigned long long int limit = 10e4;
    long long parts = 0;
    int extra = 0;
    int mainArrayIndex = 0;

    for(int i = 0; i<n/2; i++){
        temp = arr[i];
        arr[i] = arr[n-i-1];
        arr[n-i-1] = temp;
    }

    for(int i = 0; i < n; i++){
        parts = floor((arr[i] - 1) / (limit)) + 1;
        limit = arr[i] / parts;
        extra = arr[i] % parts;

        for(int index = 0; index < extra; index++){
            resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);

            arrSorted[mainArrayIndex] =     limit+1;
            mainArrayIndex+=1;
            sortedArrayLength+=1;
        }

        for(int index = 0; index < parts - extra; index++){
            resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);
            arrSorted[mainArrayIndex] =     limit;
            mainArrayIndex+=1;
            sortedArrayLength+=1;
        }

    }

    cout << "Array sorted steps taken" << " " << sortedArrayLength - arrLength;
    cout << endl;

    for(int i = 0; i < sortedArrayLength; i++){
        if(i == 0)
            cout <<  "[";

        cout << arrSorted[i];
        if(i < sortedArrayLength - 1)
            cout << ", ";

        if(i == sortedArrayLength - 1)
            cout << "]";
    }

    delete []arr;
    delete []arrSorted;

}
tv6aics1

tv6aics11#

您的辅助函数的orig = resized;没有按照您的意愿重新分配主函数的arrSorted

void resizeArray(int *&orig, ...) {

(That以及缺乏包括iostream是我看到的唯一正确性问题,这个修复程序消除了这个错误。)

相关问题