内存泄漏递归传递动态变量
Memory leaks passing dynamic variables recursively
我有一个递归功能,要求我每次调用函数时都创建一个新数组。该功能还需要以前创建的数组:
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;
}
相关文章:
- 如果非动态变量被指针引用,何时超出范围?
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- C++ 卷曲后动态变量
- 动态变量 cpp 编译
- 将删除运算符放置在何处以进行动态变量
- cpp 中的析构函数是否自动调用?即使析构函数没有提及非动态变量,它们也会被删除吗?
- C++动态变量和未定义内存之间的差异
- 动态变量名称构建,连接
- XML文件中的动态变量和函数调用
- 动态变量上的c++MACRO未声明标识符
- 内存泄漏递归传递动态变量
- 获取具有动态变量的结构的大小
- 创建动态变量
- C++:如何在类中获取具有动态变量的私有属性
- 基于 txt 文件的动态变量
- C++:使用宏字符串将项目转换为动态变量的简单方法
- 通过引用传递动态变量的指针
- 静态与堆栈动态变量的访问效率
- 指针、动态变量C++
- 来自c++指针的c#动态变量