SIGSEGV (Segmentation fault) on freeing memory vtkSmartPointer<vtkImageData> (NIFTY)

Hello support comumity,

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:

  1. You create a smart pointer.
  2. You assign an object called to the smart pointer.
  3. You call Delete() on the object. Now the smart pointer is dangling, because it points to an object that has been destroyed.
  4. 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.

Use of a smart pointer is clearly the best/cleaner way. Another one without it, is simply to increment the reference counter on the data object:

  auto data = reader->GetOutput();
  this->niimg = data;
  this->niimg->Register(nullptr);

In this case, when the reader deletes the output data, it actually just decrements its reference counter.
Hope this helps,
J.