From 89802bd12c723087af8bb7034383efd4793c413b Mon Sep 17 00:00:00 2001
From: Mathieu Westphal <mathieu.westphal@kitware.com>
Date: Mon, 29 May 2017 16:46:52 +0200
Subject: [PATCH] Fix some memory leaks in vtkSphereTree and cleanup api

---
 Common/ExecutionModel/vtkSphereTree.cxx | 28 +++++++++++--------------
 Common/ExecutionModel/vtkSphereTree.h   |  2 +-
 2 files changed, 13 insertions(+), 17 deletions(-)

diff --git a/Common/ExecutionModel/vtkSphereTree.cxx b/Common/ExecutionModel/vtkSphereTree.cxx
index a2977247a5..cbea6b29ae 100644
--- a/Common/ExecutionModel/vtkSphereTree.cxx
+++ b/Common/ExecutionModel/vtkSphereTree.cxx
@@ -1079,21 +1079,13 @@ vtkSphereTree::vtkSphereTree()
 vtkSphereTree::~vtkSphereTree()
 {
   this->SetDataSet(nullptr);
-  if ( this->Selected )
-  {
-    delete [] this->Selected;
-    this->Selected = nullptr;
-  }
+  delete[] this->Selected;
+  delete this->Hierarchy;
   if ( this->Tree )
-    {
+  {
     this->Tree->Delete();
     this->Tree = nullptr;
-    }
-  if ( this->Hierarchy )
-    {
-    delete this->Hierarchy;
-    this->Hierarchy = nullptr;
-    }
+  }
 }
 
 //================General tree methods========================================
@@ -1134,13 +1126,18 @@ void vtkSphereTree::Build(vtkDataSet *input)
 
 //----------------------------------------------------------------------------
 // Compute the sphere tree leafs (i.e., spheres around each cell)
-vtkDoubleArray *vtkSphereTree::BuildTreeSpheres(vtkDataSet *input)
+void vtkSphereTree::BuildTreeSpheres(vtkDataSet *input)
 {
   // See if anything has to be done
   if ( this->Tree != nullptr && this->BuildTime > this->MTime )
     {
-    return this->Tree;
+    return;
     }
+  else if(this->Tree != nullptr)
+  {
+    this->Tree->Delete();
+    delete[] this->Selected;
+  }
 
   // Allocate
   //
@@ -1171,8 +1168,6 @@ vtkDoubleArray *vtkSphereTree::BuildTreeSpheres(vtkDataSet *input)
   }
 
   this->BuildTime.Modified();
-
-  return newScalars;
 }
 
 //----------------------------------------------------------------------------
@@ -1368,6 +1363,7 @@ BuildUnstructuredHierarchy(vtkDataSet *input, double *tree)
 
   // We are ready to create the hierarchy
   vtkUnstructuredHierarchy *h;
+  delete this->Hierarchy; //cleanup if necessary
   this->Hierarchy = h =
     new vtkUnstructuredHierarchy(dims,bds,spacing,numCells);
   vtkIdType *cellLoc=h->CellLoc, *cellMap=h->CellMap;
diff --git a/Common/ExecutionModel/vtkSphereTree.h b/Common/ExecutionModel/vtkSphereTree.h
index 739d5343ce..d1cc4e53be 100644
--- a/Common/ExecutionModel/vtkSphereTree.h
+++ b/Common/ExecutionModel/vtkSphereTree.h
@@ -217,7 +217,7 @@ protected:
   vtkTimeStamp BuildTime; //time at which tree was built
 
   // Supporting methods
-  vtkDoubleArray *BuildTreeSpheres(vtkDataSet *input);
+  void BuildTreeSpheres(vtkDataSet *input);
   void ExtractCellIds(const unsigned char *selected, vtkIdList *cellIds,
                       vtkIdType numSelected);
 
-- 
GitLab