避免内存泄漏 [英] Avoiding memory leak

查看:115
本文介绍了避免内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在C ++学习OOP,我认为这是一个好的做法,写我自己的字符串类(当然为了学习目的)。我想出了一个我不知道如何解决的问题。这里是代码的和平:

So I was learning OOP in C++ and I thought it would be a good practice to write my own string class (for learning purposes, of course). I came up with a problem which I didn't know how to solve. Here's some peace of code:

class String {
    char *str;
public:
    String(char const *str);
    ~String();
    String operator + (char const *str);
};

String::String(char *str) {
    this->str = _strdup(str);
}

String::~String() {
    free(this->str);
}

String String::operator+(char const *str) {
    char *temp = (char *) malloc(strlen(str) + strlen(this->str) + 1);
    strcpy(temp, this->str);
    strcat(temp, str);
    return temp;
}

这里的问题是,这段代码会导致内存泄漏。从operator +返回,调用我的构造函数,它通过分配更多的内存来复制temp,我找不到任何办法如何释放它。

The problem here is, that this piece of code will cause a memory leak. Return from "operator +" invokes my constructor, which copies temp by allocating more memory and I couldn't find any way how can I free it.

推荐答案

您的运算符+ 定义为返回 String ,但返回 char * 这意味着编译器使用构造函数隐式转换它。

Your operator + is defined as returning a String but you're returning a char* which means the compiler is implicitly converting it using the constructor. This copies the string but doesn't free the original which you are therefore leaking.

有很多事情你可以做,以改善代码,正如其他人建议的,但是要修复实际的泄漏,你可以这样做:

There are lots of things you could do to improve the code, as others have suggested, but to fix the actual leak you could do this:

String String::operator+(char const *str) {
    char *temp = (char *) malloc(strlen(str) + strlen(this->str) + 1);
    strcpy(temp, this->str);
    strcat(temp, str);
    String strTmp(temp);
    free(temp);
    return strTmp;
}

这篇关于避免内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆