samedi 5 juin 2021

What happen if deallocate allocated object with malloc using delete [duplicate]

What happen if deallocate object allocated with malloc using delete?
I'm trying making ObjectPool System.
So I wrote this codes.

struct A
{
    int a;
    int b;
    int c;

    A()
    {
        std::cout << "A constructor" << std::endl;
    }
    ~A()
    {
        std::cout << "A destructor" << std::endl;
    }
};

A* a = (A*)std::malloc(sizeof(A) * 10);
    
A* a0 = a;
new (a0) A();
delete a0; 

A* a1 = a + 1;
new (a1) A();
delete a1;  

.
.
.

A* a9 = a + 9;
new (a9) A();
delete a9;  

Pooling Class allocate multiple objects.
And Pooling Class don't mind about deallocating.

But I worried Deallocating memory(allocated with malloc) using delete may make memory leak. Does this codes make memory leak?

I will never call std::free(a).
Just let user deallocate memory themself.

Aucun commentaire:

Enregistrer un commentaire