如何解决C++代码中的内存泄漏问题
How to solve problems with Memory Leaks in C++ code
这是我用来设置名称的代码
void Student::setName(const char * const name) {
this->name = new char[strlen(name)+1];
strcpy(this->name,name);
}
这是我的删除器
Student::~Student() {
perm = 0;
delete[] this->name;
}
但是当我跑瓦尔格林德时,我得到了
13 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1786== at 0x4C2FBC3: operator new[](unsigned long)
(vg_replace_malloc.c:433)
==1786== by 0x402167: Student::setName(char const*)
(student.cpp:25)
==1786== by 0x4020F1: Student::Student(char const*, int)
(student.cpp:7)
==1786== by 0x401A73: main (testStudentRoll01.cpp:11)
在
将name
已经指向的内存重新分配给新分配的内存之前,您不会delete[]
该内存。那是你的泄漏。
试试这个:
void Student::setName(const char * const name)
{
delete[] this->name; // <-- add this
this->name = NULL; // in case new[] below throws an exception...
this->name = new char[strlen(name)+1];
strcpy(this->name, name);
}
或者更好的是,使用复制和交换习惯用法来提供更好的异常安全性:
#include <algorithm>
Student::Student(const char * const name)
: name(new char[strlen(name)+1])
{
strcpy(this->name, name);
}
void Student::setName(const char * const name)
{
Student temp(name);
std::swap(this->name, temp.name);
}
此外,请确保您在类中遵循 3/5/0 规则,以避免复制赋值运算符中出现类似的泄漏(假设您甚至已经实现了一个 - 在这种情况下,默认生成的一个将泄漏)。
更好的解决方案是简单地使用 std::string
而不是 char*
,让它为您处理内存管理。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏