内存泄漏递归传递动态变量

Memory leaks passing dynamic variables recursively

本文关键字:动态 变量 泄漏 递归 内存      更新时间:2023-10-16

我有一个递归功能,要求我每次调用函数时都创建一个新数组。该功能还需要以前创建的数组:

void myFunc(int* prevArray)
{
int newSize;
//do some calculations to find newSize
int* newArray;
newArray = new int[newSize];
//do some calculations to fill newArray
//check some stopping condition
myFunc(newArray);
}

此功能泄漏了内存,但是我无法避免

避免这种情况

delete [] newarray;

因为我只能在再次调用函数后才添加。我该如何解决?

您可以通过使用动态内存分配来解决此问题。

// allocate initial size
const int INITIAL_SIZE = 5;
int *myArray = malloc(sizeof(int) * INITIAL_SIZE));
int myFunc(int *aArray, int numAllocated) {
    int numElements = calculateNewSize();
    if (numElements != numAllocated) {
        // allocate new size
        realloc(aArray, (numElements * sizeof(int));
    }
    return numElements;
}

现在您可以像这样致电myfunc:

int numElements;
numElements = myFunc(myArray, numElements);

使用MyFunc完成后,请不要忘记释放内存

free(myArray);

尝试

之类的东西
void myFunc(int* prevArray)
{
    int newSize;
    ...newArray = new int[newSize];
    myFunc(newArray);
    delete[] newArray;
}

或更好的使用STD :: unique_ptr来控制新array内存。通过这种方式,您将遵循有关动态内存的经验法则 - 它应该有一个所有者,负责分配和释放它。

您可以只使用向量并将新结果交换为最终结果。

#include <iostream>
#include <vector>
struct X { ~X() { std::cout << "Destructionn"; } };
void recursive(unsigned n, std::vector<X>& result) {
    // Put new_result in a scope for destruction
    {
        std::vector<X> new_result(1);
        // Do something
        // The previous result is no longer needed
        std::swap(result, new_result);
    }
    // Next recursion
    if(n) {
        std::cout << "Calln";
        recursive(--n, result);
    }
}
int main() {
    std::vector<X> result(1);
    std::cout << "Calln";
    recursive(3, result);
    return 0;
}