如何解决C++代码中的内存泄漏问题

How to solve problems with Memory Leaks in C++ code

本文关键字:内存 泄漏 问题 代码 C++ 何解决 解决      更新时间:2023-10-16

这是我用来设置名称的代码

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*,让它为您处理内存管理。