Why does this very simple and little C++ program terminates with -1073741819 (0xC0000005)?

0

I have a simple class with a destructor. If I instantiate an object from it with default constructor, then the program terminates succesfully, but if I instantiate it with a constructor that has any parameter, it terminates unsuccesfully.

#include <iostream>
#include <list>

class MyClass {
public:
    std::list<int>* myList;
    MyClass();
    MyClass(int a);
    ~MyClass();
};

MyClass::MyClass() {}
MyClass::MyClass(int a) {}
MyClass::~MyClass() { delete myList; }

int main()
{

    // If I do only this, the program terminates succesfully with 0 as return value
    MyClass graph1();

    // But if I do this, the program terminates unsuccesfully
    MyClass graph2(3);

    return 0;
}
c++
destructor
terminate
asked on Stack Overflow Nov 7, 2020 by PoodLee

1 Answer

8

MyClass graph1(); doesn't create an instance of MyClass, whether initialized with the default constructor or otherwise. Rather, it's a declaration of a function taking no parameters and returning MyClass. See also: most vexing parse

MyClass graph2(3); does create an instance of MyClass. Its constructor leaves myList pointer uninitialized, and then its destructor exhibits undefined behavior by way of accessing said uninitialized pointer.

answered on Stack Overflow Nov 7, 2020 by Igor Tandetnik • edited Nov 7, 2020 by Igor Tandetnik

User contributions licensed under CC BY-SA 3.0