Home > Software design >  I'm Getting error while trying to delete heap allocated int
I'm Getting error while trying to delete heap allocated int

Time:10-21

#include <iostream>
class TEST
{
public:
    int* a = new int;
    TEST(int x)
        : a(&x)
    {

    }
    ~TEST()
    {
        delete a;
    }
};

int main()
{
    {
        int i = 2;
        TEST T(i);
    }
    std::cin.get();
}

I tried to heap allocate integer in a TEST class and then delete it but when I'm calling delete a in TEST class destructor I'm getting error in file called delete_scalar.cpp and I have no idea what does it mean and how to fix it. Where's the problem?

CodePudding user response:

TEST(int x)
    : a(&x)
{

}

This code is causing undefined behavior. It is making a point at a local int that goes out of scope immediately afterwards, leaving a as a dangling pointer to invalid memory. a is never pointing at dynamic memory (the new expression in the declaration of a is ignored when a is initialized in the constructor's member initialization list). That is why the delete fails later.

To do what you are attempting, you need to either:

  • move the new into the initialization list, eg:
int* a = nullptr;
    
TEST(int x)
    : a(new int(x))
{

}
  • Or, if you want to keep using new in the declaration of a, then you can assign the value of that int from inside the constructor's body instead of in its initialization list, eg:
int* a = new int;
    
TEST(int x)
{
    *a = x;
}
  • Related