【C++】为啥会内存泄露

先来看这个类定义:

class String
{
protected:
    struct StrNode
    {
        int ref;  // 引用计数
        int len;  // 字符串的长度
        int size; // 柔性数组的容量
        char data[];
    };
private:
    StrNode* pstr;
}


下面是构造函数:

```c++
String(const char* p = NULL) :pstr(NULL)
    {
        if (p != NULL)
        {
            int sz = strlen(p);
            pstr = (StrNode*)malloc(sizeof(StrNode) + sz * 2 + 1);
            pstr->ref = 1;
            pstr->len = sz;
            pstr->size = sz * 2;
            strcpy(pstr->data, p);
        }
    }
    ~String()    //析构函数
    {
        if (pstr != NULL && --pstr->ref == 0)
        {
            free(pstr);
        }
        pstr = NULL;
    }
    String(const String& str) :pstr(NULL)    //拷贝构造函数
    {
        if (str.pstr != NULL)
        {
            pstr = str.pstr;
            pstr->ref += 1;
        }
    }

主函数调用:  为了实现s1 = s1 + s4这个功能
int main()
{
    String s1("yhping");
    String s2(s1);

    String s3("hello");
    String s4("hahaha");

    s1 = s1 + s4;
}




下面是为了完成s1 = s1 + s4而重写的+函数
String operator+(const String& s) const
    {
        if (pstr == NULL && s.pstr == NULL)
        {
            return String();
        }
        else if (pstr != NULL && s.pstr == NULL)
        {
            return *this;
        }
        else if (pstr == NULL && s.pstr != NULL)
        {
            return s;
        }
        else
        {
            int total = (pstr->len + s.pstr->len) * 2;
            StrNode* newsp = (StrNode*)malloc(sizeof(StrNode) + total + 1);
            strcpy(newsp->data, pstr->data);
            strcat(newsp->data, s.pstr->data);
            newsp->ref = 1;
            newsp->len = pstr->len + s.pstr->len;
            newsp->size = total;
            return String(newsp);


            /*int total = (pstr->len + s.pstr->len) * 2;    //这块代码我写的   老师说会内存泄漏   让我自己去想
            char* sp = (char*)malloc(total + 1);
            strcpy(sp, pstr->data);
            strcat(sp, s.pstr->data);
            return String(sp);*/
        }
    }

使用malloc动态分配的内存要主动free才能释放

sp 用完后要用free释放掉