From 243238f382db54a74639e05058c314133255746c Mon Sep 17 00:00:00 2001
From: Nick Draper <nick.draper@stfc.ac.uk>
Date: Tue, 13 Oct 2015 14:49:54 +0100
Subject: [PATCH] coverity fixes  Null pointer dereferences

re #13938
---
 Framework/API/src/Algorithm.cpp               | 12 ++++++-----
 Framework/API/src/FunctionFactory.cpp         |  3 +++
 Framework/Crystal/src/FilterPeaks.cpp         |  3 +++
 .../Instrument/InstrumentDefinitionParser.cpp |  4 +++-
 Framework/Kernel/src/Matrix.cpp               | 21 +++++++++++--------
 .../src/IntegrateMDHistoWorkspace.cpp         |  4 ++++
 .../WorkflowAlgorithms/src/RefReduction.cpp   |  2 ++
 MantidPlot/src/ConfigDialog.cpp               |  7 +++++--
 MantidPlot/src/ContourLinesEditor.cpp         | 10 ++++++---
 MantidPlot/src/CustomActionDialog.cpp         |  5 ++++-
 MantidPlot/src/ScaleDetails.cpp               |  4 ++++
 Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp  |  6 +++++-
 12 files changed, 59 insertions(+), 22 deletions(-)

diff --git a/Framework/API/src/Algorithm.cpp b/Framework/API/src/Algorithm.cpp
index e95b083c084..860a17a3d66 100644
--- a/Framework/API/src/Algorithm.cpp
+++ b/Framework/API/src/Algorithm.cpp
@@ -1278,11 +1278,13 @@ bool Algorithm::processGroups() {
   // ---------- Create all the output workspaces ----------------------------
   for (size_t owp = 0; owp < m_pureOutputWorkspaceProps.size(); owp++) {
     Property *prop = dynamic_cast<Property *>(m_pureOutputWorkspaceProps[owp]);
-    WorkspaceGroup_sptr outWSGrp = WorkspaceGroup_sptr(new WorkspaceGroup());
-    outGroups.push_back(outWSGrp);
-    // Put the GROUP in the ADS
-    AnalysisDataService::Instance().addOrReplace(prop->value(), outWSGrp);
-    outWSGrp->observeADSNotifications(false);
+    if (prop) {
+      WorkspaceGroup_sptr outWSGrp = WorkspaceGroup_sptr(new WorkspaceGroup());
+      outGroups.push_back(outWSGrp);
+      // Put the GROUP in the ADS
+      AnalysisDataService::Instance().addOrReplace(prop->value(), outWSGrp);
+      outWSGrp->observeADSNotifications(false);
+    }
   }
 
   // Go through each entry in the input group(s)
diff --git a/Framework/API/src/FunctionFactory.cpp b/Framework/API/src/FunctionFactory.cpp
index 5d2a0a1aad4..29a5ec54767 100644
--- a/Framework/API/src/FunctionFactory.cpp
+++ b/Framework/API/src/FunctionFactory.cpp
@@ -192,6 +192,9 @@ CompositeFunction_sptr FunctionFactoryImpl::createComposite(
     inputError(expr.str());
   }
 
+  if (!cfun)
+    inputError(expr.str());
+
   for (; it != terms.end(); ++it) {
     const Expression &term = it->bracketsRemoved();
     IFunction_sptr fun;
diff --git a/Framework/Crystal/src/FilterPeaks.cpp b/Framework/Crystal/src/FilterPeaks.cpp
index 8e398c2b0de..2c92154e77e 100644
--- a/Framework/Crystal/src/FilterPeaks.cpp
+++ b/Framework/Crystal/src/FilterPeaks.cpp
@@ -98,6 +98,9 @@ void FilterPeaks::exec() {
     filterFunction = &intensity;
   else if (FilterVariable == "Signal/Noise")
     filterFunction = &SN;
+  else
+      throw std::invalid_argument(
+        "Unknown FilterVariable: " + FilterVariable);
 
   const double FilterValue = getProperty("FilterValue");
   const std::string Operator = getProperty("Operator");
diff --git a/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp b/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp
index cdc50169d55..223a17b6028 100644
--- a/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp
+++ b/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp
@@ -2301,7 +2301,9 @@ void InstrumentDefinitionParser::createNeutronicInstrument() {
             mapTypeNameToShape.find(shapeName);
         if (shapeIt != mapTypeNameToShape.end()) {
           // Change the shape on the current component to the one requested
-          dynamic_cast<ObjComponent *>(it->first)->setShape(shapeIt->second);
+          auto objCmpt = dynamic_cast<ObjComponent *>(it->first);
+          if (objCmpt)
+            objCmpt->setShape(shapeIt->second);
         } else {
           throw Exception::InstrumentDefinitionError(
               "Requested type " + shapeName + " not defined in IDF");
diff --git a/Framework/Kernel/src/Matrix.cpp b/Framework/Kernel/src/Matrix.cpp
index f4e1adc1319..c8edd12b2ce 100644
--- a/Framework/Kernel/src/Matrix.cpp
+++ b/Framework/Kernel/src/Matrix.cpp
@@ -158,17 +158,20 @@ Matrix<T>::Matrix(const Matrix<T> &A, const size_t nrow, const size_t ncol)
     throw Kernel::Exception::IndexError(ncol, A.ny,
                                         "Matrix::Constructor without col");
   setMem(nx, ny);
-  size_t iR(0);
-  for (size_t i = 0; i <= nx; i++) {
-    if (i != nrow) {
-      size_t jR(0);
-      for (size_t j = 0; j <= ny; j++) {
-        if (j != ncol) {
-          V[iR][jR] = A.V[i][j];
-          jR++;
+  if (!V) {
+    size_t iR(0);
+    for (size_t i = 0; i <= nx; i++) {
+      if (i != nrow) {
+        size_t jR(0);
+        for (size_t j = 0; j <= ny; j++) {
+          if (j != ncol) {
+
+              V[iR][jR] = A.V[i][j];
+              jR++;
+          }
         }
+        iR++;
       }
-      iR++;
     }
   }
 }
diff --git a/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp b/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp
index 711de48f4bf..1468a6001c3 100644
--- a/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp
+++ b/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp
@@ -386,6 +386,10 @@ void IntegrateMDHistoWorkspace::exec() {
         // Create a thread-local input iterator.
         boost::scoped_ptr<MDHistoWorkspaceIterator> inIterator(
             dynamic_cast<MDHistoWorkspaceIterator *>(inWS->createIterator()));
+        if (!inIterator) {
+          throw std::runtime_error(
+              "Could not convert IMDIterator to a MDHistoWorkspaceIterator");
+        }
 
         /*
         We jump to the iterator position which is closest in the model
diff --git a/Framework/WorkflowAlgorithms/src/RefReduction.cpp b/Framework/WorkflowAlgorithms/src/RefReduction.cpp
index 4ece40c1ee5..9b111d80d45 100644
--- a/Framework/WorkflowAlgorithms/src/RefReduction.cpp
+++ b/Framework/WorkflowAlgorithms/src/RefReduction.cpp
@@ -629,6 +629,8 @@ double RefReduction::calculateAngleREFM(MatrixWorkspace_sptr workspace) {
   Mantid::Kernel::Property *prop = workspace->run().getProperty("SampleDetDis");
   Mantid::Kernel::TimeSeriesProperty<double> *dp =
       dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(prop);
+  if (!dp) throw std::runtime_error(
+    "SampleDetDis was not a TimeSeriesProperty");
   const double det_distance = dp->getStatistics().mean / 1000.0;
 
   double direct_beam_pix = getProperty("DirectPixel");
diff --git a/MantidPlot/src/ConfigDialog.cpp b/MantidPlot/src/ConfigDialog.cpp
index 6344d67d31c..87e74e4ea83 100644
--- a/MantidPlot/src/ConfigDialog.cpp
+++ b/MantidPlot/src/ConfigDialog.cpp
@@ -2341,8 +2341,11 @@ void ConfigDialog::apply()
   QList<MdiSubWindow*> windows = app->windowsList();
   foreach(MdiSubWindow *w, windows){
     if (w->isA("MultiLayer")){
-      (dynamic_cast<MultiLayer*>(w))->setScaleLayersOnPrint(boxScaleLayersOnPrint->isChecked());
-      (dynamic_cast<MultiLayer*>(w))->printCropmarks(boxPrintCropmarks->isChecked());
+      MultiLayer* multiLayer = dynamic_cast<MultiLayer*>(w);
+      if (multiLayer) {
+        multiLayer->setScaleLayersOnPrint(boxScaleLayersOnPrint->isChecked());
+        multiLayer->printCropmarks(boxPrintCropmarks->isChecked());
+      }
     }
   }
   // general page: application tab
diff --git a/MantidPlot/src/ContourLinesEditor.cpp b/MantidPlot/src/ContourLinesEditor.cpp
index 19ff48b3bf2..144b2c7f245 100644
--- a/MantidPlot/src/ContourLinesEditor.cpp
+++ b/MantidPlot/src/ContourLinesEditor.cpp
@@ -108,10 +108,14 @@ void ContourLinesEditor::updateContourLevels()
 
 	int rows = table->rowCount();
 	QwtValueList levels;
-	for (int i = 0; i < rows; i++)
-		levels << dynamic_cast<DoubleSpinBox*>(table->cellWidget(i, 0))->value();
+  for (int i = 0; i < rows; i++) {
+    DoubleSpinBox *spinBox =
+        dynamic_cast<DoubleSpinBox *>(table->cellWidget(i, 0));
+    if (spinBox)
+      levels << spinBox->value();
+  }
 
-	d_spectrogram->setContourLevels(levels);
+  d_spectrogram->setContourLevels(levels);
 }
 
 void ContourLinesEditor::updateContourPens()
diff --git a/MantidPlot/src/CustomActionDialog.cpp b/MantidPlot/src/CustomActionDialog.cpp
index 0ffe7922476..8b779deb8ec 100644
--- a/MantidPlot/src/CustomActionDialog.cpp
+++ b/MantidPlot/src/CustomActionDialog.cpp
@@ -514,7 +514,10 @@ void CustomActionDialog::chooseFolder()
 QAction * CustomActionDialog::actionAt(int row)
 {
 	ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
-	QList<QAction *>actions = app->customActionsList();
+  if (!app)
+    throw std::runtime_error(
+        "The parent of this dialog was not the Application Window");
+  QList<QAction *>actions = app->customActionsList();
 	if (actions.isEmpty() || row < 0 || row >= actions.count())
         return 0;
 
diff --git a/MantidPlot/src/ScaleDetails.cpp b/MantidPlot/src/ScaleDetails.cpp
index 71190376094..e6ef88b1031 100644
--- a/MantidPlot/src/ScaleDetails.cpp
+++ b/MantidPlot/src/ScaleDetails.cpp
@@ -272,6 +272,10 @@ void ScaleDetails::initWidgets()
     if (type == ScaleDraw::Date)
     {
       ScaleDraw *sclDraw = dynamic_cast<ScaleDraw *>(d_plot->axisScaleDraw(m_mappedaxis));
+      if (!sclDraw) {
+        throw std::runtime_error("Could not convert the axis Scale Draw object "
+                                 "to a ScaleDraw object");
+      }
       QDateTime origin = sclDraw->dateTimeOrigin();
 
       m_dspnStart->hide();
diff --git a/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
index 748722813c5..11af3df2b5b 100644
--- a/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
+++ b/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp
@@ -120,7 +120,11 @@ namespace Mantid
         double progressFactor = 0.5/double(nBinsX);
         double progressOffset = 0.5;
         boost::scoped_ptr<MDHistoWorkspaceIterator> iterator(dynamic_cast<MDHistoWorkspaceIterator*>(createIteratorWithNormalization(m_normalizationOption, m_workspace.get())));
-    
+        if (!iterator) {
+          throw std::runtime_error(
+              "Could not convert IMDIterator to a MDHistoWorkspaceIterator");
+        }
+
         size_t index = 0;
         for (int i = 0; i < nBinsX; i++)
         {
-- 
GitLab