How to understand that value of C++ class member variable is not consistent in destructor function

89 Views Asked by At

I write a demo to test dustructor behavior, and the output result is not as expected. Can anyone tell me why?

The source code is as follow:

    #include <iostream>
    #include <cstring>
    #include <cstdlib>
    using namespace std;
    class Str{
    private:
        char *pstr;
    public:
        Str(char value[])
        {
            cout<<this<<":constructor called"<<endl;
            pstr = NULL;
            int len = strlen(value);
            pstr = (char *)malloc(len + 1);
            memset(pstr,0,len + 1);
            strcpy(pstr,value);
        }
        ~Str()
        {
            cout<<this<<":destructor called, "<<(long)pstr<<endl;
            if(pstr != NULL)
            {
                cout<<this<<":destructor call free() "<<endl;
                free(pstr);
                pstr = NULL;
            }
        }
    };
    int main()
    {
        Str *p = new Str("aaa");
        delete p;
        delete p; //make destuctor called twice.
        return 0; 
    }

The output of the program is as folows:

0x600001240040:constructor called
0x600001240040:destructor called, 105553135403088
0x600001240040:destructor call free()
0x600001240040:destructor called, 255133788340288
0x600001240040:destructor call free()
a.out(71425,0x1fdc8e080) malloc: *** error for object 0xe80af6d30040: pointer being freed was not allocated
a.out(71425,0x1fdc8e080) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

Look at the output, why the member variable "pstr" is not null for the second calling of destructor?

It was obviously asigned null in the first calling of destructor.

0

There are 0 best solutions below