我有一个递归函数,每次调用该函数时都需要创建一个新数组。该函数还需要先前创建的数组:
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);
关于c++ - 递归传递动态变量的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21401353/