I have Segmentation fault error when I am freeing memory.
(I use nifty reader to get an image)
Here how my parts of source code look like :
class NiftiImage {
private:
vtkSmartPointer niimg = nullptr;
WRITING OF VARIABLE
auto data = reader->GetOutput();
this->niimg = data;
DELETION PART (DESTRUCTOR)
if (this->niimg != nullptr) {
this->niimg->Delete();
this->niimg= nullptr; //HERE IT FAILS
}
if (this->bspline_coeff != nullptr) {
this->bspline_coeff->Delete();
}
I don’t sure what is happening here. Usually, this error occurs when you trying to access unaccessible memory or double clearing of memory. I use the latest build of VTK 9
Your use of Delete() results in a dangling pointer. Here is what you are doing:
You create a smart pointer.
You assign an object called to the smart pointer.
You call Delete() on the object. Now the smart pointer is dangling, because it points to an object that has been destroyed.
You set the smart pointer to “nullptr”, which causes the smart pointer to call Delete() on the object again (via the dangling pointer). This causes a segfault.
The solution is simple. Do not destroy an object that is held by a smart pointer. To destroy the object, you should either assign a new value to the smart pointer (e.g. nullptr), or allow the smart pointer to destruct.