I'm trying to make a program work in c++. When I create an instance of a class and take the reference to it, everything is fine:
PolyCRTBuilder test1(parms);
PolyCRTBuilder *p = &test1;
But when I use dynamic allocation to create the instance, it gives me a segmentation fault error as I try to free the memory:
PolyCRTBuilder *test2 = new PolyCRTBuilder(parms);
cout << "test2 variable created" << endl;
delete [] test2;
cout << "test2 variable deleted" << endl;
This last code returns me
test2 variable created
Segmentation fault
Why is this?
delete [] test2;
deletes an array, but you create a normal object. Try delete test2;
instead.
You should also familiarize youself with smart pointers, for example unique_ptr and shared_ptr. Raw pointers are bad style in modern C++ and makes you program error prone.