简体   繁体   中英

Destructor to call free() to free dynamically allocated memory using malloc

In C++, if I have some dynamically allocated memory using malloc, can I free the same by calling free() from destructor and then explicitly call the destructor via class object?

Trying to do that but getting an exception.

Is it now allowed?

So here I'm explicitly calling the destructor. Is this allowed? I mean, I'm calling it to free memory. I did read that after the scope, the destructor is called implicitly. Does this mean the free() will try to happen twice?

My code snippet:

class School
{
    int a;
};

class Test
{
    public:
    School* school;
    void Run()
    {
        school = (School*)malloc(sizeof(School));
    }
    
    ~Test()
    {
        if (NULL != school)
        {
            free(school);
            school = NULL;
        }
    }
};

int main()
{
    Test t;
    t.Run();
    t.~Test();
    return 0;
}

Your code destroys t twice. It is destroyed first when you call the destructor and then again when it goes out of scope. You cannot create one object and then destroy two objects.

You can explicitly call the destructor, and that has sense whenever you create the object using an placement new .

You may get an exception if you have the opposite order of operations. First you need to call the destructor, as it needs to free all the resources that the object may have allocated. You need to call the free function only after all resources of the object are deallocated/destroyed. For example:

struct S {
    ~S() {
        delete ptr;
    }
    int *ptr;
};

int main() {
    char *buf = (char*) malloc(sizeof(S)) ;
    S *s = new (buf)S();
    // Do not call free here as the destructor needs to access the s.ptr:
    //free(buf);
    s->~S();
    free(buf);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM