double free ERR一种常见形式

double free ERR:

容易发生在含有指针的类等于“=”操作之后(几个类的指针成员这是其实指向了同一个地址),当每个类析构函数delete指针的时候其实对同一个地址进行了free,那么就导致double free的错误。

所以类中含有指针成员的时候尽量不要进行类的等于操作。

如果类非得用等于操作,那么就类不能用含有指针成员

/*double free ERR test ,when class operate = ,add by ygx ,2021.05.21*/
class Tool
{
private :
    int a{0};
};
class A
{
public:
    A()
    {
        pTool = new Tool();
    }
     ~A()
    {
        if(pTool)
        {
            delete pTool;
            pTool = NULL;
        }
    }

private:
    Tool * pTool;
};

class Test_copy
{
public:
    Test_copy() =default;
    void test()
    {
        cur_A = pre_A;// this time ,cur_A->pTool was set to pre_A->pTool ,they point to the same adress ,so when in A::~A() ,in fact, free the same adress twice, caused double free ERR,
    }
private:
    A cur_A;
    A pre_A;
};


inline void double_free_test()
{
    //
    Test_copy test1;
    test1.test();
}

 

おすすめ

転載: blog.csdn.net/dbdxnuliba/article/details/117130124
おすすめ