删除 [] 后内存泄漏
Memory Leak after delete []
我遇到了内存泄漏问题,我无法弄清楚可能导致它的原因。我有一个包含数组的结构。我偶尔需要调整数组的大小,所以我创建了一个长度是旧数组两倍的新数组,并复制所有旧值。然后我用"delete [] 数组"删除数组,并用新数组重新分配旧数组。
struct Structure {
double* array = new double[1]
int capacity = 1;
}
void resize (Structure& structure) {
double* array = new double[structure.capacity * 2];
for (int i = 0; i < structure.capacity; i++) {
array[i] = structure.array[i];
}
delete [] structure.array;
structure.array = array;
}
我希望旧数组被释放并替换为新数组。相反,我收到内存泄漏错误。
==91== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==91== at 0x4C3089F: operator new[](unsigned long)
您的结构不遵循 3/5/0 规则,特别是当结构本身被销毁时,它缺少一个析构函数来delete[]
当前array
:
struct Structure {
double* array = new double[1];
int capacity = 1;
~Structure() { delete[] array; } // <-- add this!
/* also, you should add these, too:
Structure(const Structure &)
Structure(Structure &&)
Structure& operator=(const Structure &)
Structure& operator=(Structure &&)
*/
};
您确实应该使用std::vector<double>
而不是直接使用new[]
。std::vector
处理您尝试手动执行的所有操作,并且比您更安全:
#include <vector>
struct Structure {
std::vector<double> array;
Structure() : array(1) {}
};
void resize (Structure& structure) {
structure.array.resize(structure.array.size() * 2);
}
或:
#include <vector>
struct Structure {
std::vector<double> array;
Structure() { array.reserve(1); }
};
void resize (Structure& structure) {
structure.array.reserve(structure.array.capacity() * 2);
}
取决于您实际使用array
的方式。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏