From 9b9c2624f10daae07e7bd77bfc80f4f5e798d026 Mon Sep 17 00:00:00 2001
From: Guillaume Pasero <guillaume.pasero@c-s.fr>
Date: Wed, 6 Jan 2016 17:39:18 +0100
Subject: [PATCH] COV: various coverity fix

---
 Examples/Projections/SensorModelExample.cxx   |  4 +--
 .../LAIAndPROSAILToSensorResponse.cxx         | 10 ++++--
 .../app/otbDSFuzzyModelEstimation.cxx         | 16 +++++++---
 .../app/otbLSMSSmallRegionsMerging.cxx        |  4 +--
 .../test/otbBandMathImageFilter.cxx           | 30 +++++++++--------
 .../otbMorphologicalPyramidMRToMSConverter.h  |  2 +-
 ...otbMorphologicalPyramidMRToMSConverter.txx |  2 +-
 .../otbStreamingStatisticsImageFilter.txx     | 28 ++++++++++------
 .../otbConfusionMatrixMeasurements.txx        | 32 +++++++++++++------
 .../Simulation/src/otbSailModel.cxx           |  4 +--
 10 files changed, 84 insertions(+), 48 deletions(-)

diff --git a/Examples/Projections/SensorModelExample.cxx b/Examples/Projections/SensorModelExample.cxx
index d8753bcb4b..b162762e69 100644
--- a/Examples/Projections/SensorModelExample.cxx
+++ b/Examples/Projections/SensorModelExample.cxx
@@ -472,8 +472,8 @@ int main(int argc, char* argv[])
 
       outputImage->SetPixel(currentIndexBis, pixelValue);
       }
-    delete pixelIndexArray;
-    delete currentIndexArray;
+    delete[] pixelIndexArray;
+    delete[] currentIndexArray;
 
     }
 // Software Guide : EndCodeSnippet
diff --git a/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx b/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx
index f49bb64095..38c27e8133 100644
--- a/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx
+++ b/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx
@@ -102,16 +102,15 @@ public:
 
   ArrayType GetUniqueValues() const
   {
+    ArrayType uniqueValues;
     if( !m_Image )
       {
-       itkExceptionMacro(<<"GetUniqueValues(): Null input image pointer.");
+      return uniqueValues;
       }
 
     itk::ImageRegionConstIterator< ImageType > it( m_Image,
                                               m_Image->GetRequestedRegion() );
 
-    ArrayType uniqueValues;
-
     uniqueValues.push_back(it.Get());
     ++it;
     while( !it.IsAtEnd() )
@@ -758,6 +757,11 @@ int main(int argc, char *argv[])
 
   UniqueCalculatorType::ArrayType uniqueVals =
       uniqueCalculator->GetUniqueValues();
+  if (uniqueVals.empty())
+    {
+    std::cerr << "No label value found!"<< std::endl;
+    return EXIT_FAILURE;
+    }
   std::cout << "Labels are " << std::endl;
   UniqueCalculatorType::ArrayType::const_iterator uvIt = uniqueVals.begin();
 
diff --git a/Modules/Applications/AppClassification/app/otbDSFuzzyModelEstimation.cxx b/Modules/Applications/AppClassification/app/otbDSFuzzyModelEstimation.cxx
index 2f8a942ea8..cd7c988361 100644
--- a/Modules/Applications/AppClassification/app/otbDSFuzzyModelEstimation.cxx
+++ b/Modules/Applications/AppClassification/app/otbDSFuzzyModelEstimation.cxx
@@ -261,6 +261,10 @@ private:
         accNbElemPS++;
         }
       }
+    if (accNbElemPS == 0)
+      {
+      otbAppLogFATAL(<< "Error : no element found in positive vector data!");
+      }
 
     TreeIteratorType itVectorNS(nsVectorData->GetDataTree());
     std::vector<double> accFirstOrderNS, accSecondOrderNS, minNS, maxNS;
@@ -300,6 +304,10 @@ private:
         accNbElemNS++;
         }
       }
+    if (accNbElemNS == 0)
+      {
+      otbAppLogFATAL(<< "Error : no element found in negative vector data!");
+      }
     otbAppLogINFO( << "Descriptors Stats : ");
     otbAppLogINFO( << "Positive Samples");
     for (unsigned int i = 0; i < descList.size(); ++i)
@@ -406,11 +414,9 @@ private:
       {
       // An error has occurred in the optimization.
       // Update the parameters
-      otbAppLogFATAL("ERROR: Exception Catched!" << std::endl);
-      otbAppLogFATAL(<< err.GetDescription() << std::endl);
-      const unsigned int numberOfIterations = m_Optimizer->GetOptimizer()->get_num_evaluations();
-      otbAppLogFATAL("numberOfIterations : " << numberOfIterations << std::endl);
-      otbAppLogFATAL("Results : " << m_Optimizer->GetCurrentPosition() << std::endl);
+      otbAppLogFATAL("ERROR: Exception Catched : "<< err.GetDescription() << std::endl
+        << "numberOfIterations : " << m_Optimizer->GetOptimizer()->get_num_evaluations() << std::endl
+        << "Results : " << m_Optimizer->GetCurrentPosition() << std::endl);
       }
     // get the results
     const unsigned int numberOfIterations = m_Optimizer->GetOptimizer()->get_num_evaluations();
diff --git a/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx b/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx
index c2122b50ba..64156f9eda 100644
--- a/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx
+++ b/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx
@@ -325,8 +325,8 @@ private:
               if(nbPixels[curLabel]==size)
                 {
                 edgeLabel.insert(curLabel);
-                for(std::set<int>::iterator itAdjLabel=adjMap[curLabel].begin();
-                    itAdjLabel!=adjMap[curLabel].end(); ++itAdjLabel)
+                for(std::set<int>::iterator itAdjLabel=(adjMap[curLabel]).begin();
+                    itAdjLabel!=(adjMap[curLabel]).end(); ++itAdjLabel)
                   {
                   double tmpError = 0;
                   LabelImagePixelType tmpLabel = *itAdjLabel;
diff --git a/Modules/Filtering/MathParser/test/otbBandMathImageFilter.cxx b/Modules/Filtering/MathParser/test/otbBandMathImageFilter.cxx
index 499e5b864e..f18f325a57 100644
--- a/Modules/Filtering/MathParser/test/otbBandMathImageFilter.cxx
+++ b/Modules/Filtering/MathParser/test/otbBandMathImageFilter.cxx
@@ -138,22 +138,17 @@ int otbBandMathImageFilter( int itkNotUsed(argc), char* itkNotUsed(argv) [])
     error = (result - expected) * (result - expected) / (result + expected);
     if ( error > 1E-9 )
       {
-      itkGenericExceptionMacro(  <<std::endl
+      std::cout
          << "Error = " << error << "  > 1E-9     -> TEST FAILLED" << std::endl
          << "Pixel_1 =  "       << it1.Get()
          << "     Pixel_2 =  "  << it2.Get()
          << "     Pixel_3 =  "  << it3.Get()
          << "     Result =  "   << it.Get()
-         << "     Expected =  " << expected     << std::endl );
+         << "     Expected =  " << expected << std::endl;
       FAIL_FLAG++;
+      break;
       }
-  }
-  if(!FAIL_FLAG)
-    std::cout << "[PASSED]" << std::endl;
-  else
-    std::cout << "[FAILLED]" << std::endl;
-  FAIL_FLAG = 0;
-
+    }
 
 
   /** Edge Effect Handling */
@@ -166,14 +161,23 @@ int otbBandMathImageFilter( int itkNotUsed(argc), char* itkNotUsed(argv) [])
   it1.GoToBegin(); it2.GoToBegin(); it.GoToBegin();
   for(i=1; i<=50; ++i , ++it1, ++it2, ++it){}
   if(vnl_math_isnan(it.Get()))
-    std::cout << "Pixel_1 =  " << it1.Get() << "     Pixel_2 =  " << it2.Get() << "     Result =  " << it.Get() << "     Expected =  nan\n";
+    std::cout << "Pixel_1 =  " << it1.Get() << "     Pixel_2 =  " << it2.Get() << "     Result =  " << it.Get() << "     Expected =  nan\n" << std::endl;
   else
-    itkGenericExceptionMacro(
+    {
+    std::cout
              << "\nError > Bad Edge Effect Handling -> Test Failled\n"
              << "Pixel_1 =  "     << it1.Get()  << "     Pixel_2 =  "  << it2.Get()
-             << "     Result =  " << it.Get()   << "     Expected =  nan\n" );
-  std::cout << std::endl;
+             << "     Result =  " << it.Get()   << "     Expected =  nan\n" << std::endl;
+    FAIL_FLAG++;
+    }
+
+  if (FAIL_FLAG)
+    {
+    std::cout << "[FAILLED]" << std::endl;
+    return EXIT_FAILURE;
+    }
 
+  std::cout << "[PASSED]" << std::endl;
   return EXIT_SUCCESS;
 }
 
diff --git a/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.h b/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.h
index 3c8bb76d2d..ed0d020562 100644
--- a/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.h
+++ b/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.h
@@ -68,7 +68,7 @@ public:
    * \param imageList The analysed image at each level of the pyramid.
    */
   using Superclass::SetInput;
-  void SetInput(InputImageListType * imageList);
+  void SetInput(const InputImageListType * imageList);
   /**
    * Set The SupFilter details
    * \param imageList The brighter details extracted from the filtering operation.
diff --git a/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.txx b/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.txx
index 33bdc36576..3c26e6f695 100644
--- a/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.txx
+++ b/Modules/Filtering/MorphologicalPyramid/include/otbMorphologicalPyramidMRToMSConverter.txx
@@ -118,7 +118,7 @@ MRToMSConverter<TInputImage, TOutputImage>
 template <class TInputImage, class TOutputImage>
 void
 MRToMSConverter<TInputImage, TOutputImage>
-::SetInput(InputImageListType * imageList)
+::SetInput(const InputImageListType * imageList)
 {
   this->SetNthInput(2, const_cast<InputImageListType *>(imageList));
 }
diff --git a/Modules/Filtering/Statistics/include/otbStreamingStatisticsImageFilter.txx b/Modules/Filtering/Statistics/include/otbStreamingStatisticsImageFilter.txx
index 5a873618be..328f517d8a 100644
--- a/Modules/Filtering/Statistics/include/otbStreamingStatisticsImageFilter.txx
+++ b/Modules/Filtering/Statistics/include/otbStreamingStatisticsImageFilter.txx
@@ -240,9 +240,9 @@ PersistentStatisticsImageFilter<TInputImage>
 
   PixelType minimum;
   PixelType maximum;
-  RealType  mean;
-  RealType  sigma;
-  RealType  variance;
+  RealType  mean = itk::NumericTraits<RealType>::Zero;
+  RealType  sigma = itk::NumericTraits<RealType>::Zero;
+  RealType  variance = itk::NumericTraits<RealType>::Zero;
   RealType  sum;
 
   sum = sumOfSquares = itk::NumericTraits<RealType>::Zero;
@@ -267,13 +267,23 @@ PersistentStatisticsImageFilter<TInputImage>
       maximum = m_ThreadMax[i];
       }
     }
-  // compute statistics
-  mean = sum / static_cast<RealType>(count);
+  if (count > 0)
+    {
+    // compute statistics
+    mean = sum / static_cast<RealType>(count);
 
-  // unbiased estimate
-  variance = (sumOfSquares - (sum * sum / static_cast<RealType>(count)))
-             / (static_cast<RealType>(count) - 1);
-  sigma = vcl_sqrt(variance);
+    if (count > 1)
+      {
+      // unbiased estimate
+      variance = (sumOfSquares - (sum * sum / static_cast<RealType>(count)))
+             / static_cast<RealType>(count - 1);
+      sigma = vcl_sqrt(variance);
+      }
+    }
+  else
+    {
+    itkWarningMacro(<<"No pixel found to compute statistics!");
+    }
 
   // Set the outputs
   this->GetMinimumOutput()->Set(minimum);
diff --git a/Modules/Learning/Supervised/include/otbConfusionMatrixMeasurements.txx b/Modules/Learning/Supervised/include/otbConfusionMatrixMeasurements.txx
index 3cdf66f91d..da4dcb4940 100644
--- a/Modules/Learning/Supervised/include/otbConfusionMatrixMeasurements.txx
+++ b/Modules/Learning/Supervised/include/otbConfusionMatrixMeasurements.txx
@@ -55,6 +55,7 @@ ConfusionMatrixMeasurements<TConfusionMatrix, TLabel>
   m_TruePositiveValues.Fill(0);
   m_TrueNegativeValues.Fill(0);
 
+  const double epsilon = 0.0000000001;
   double luckyRate = 0.;
   this->m_NumberOfSamples = 0;
   this->m_OverallAccuracy  = 0.;
@@ -83,8 +84,6 @@ ConfusionMatrixMeasurements<TConfusionMatrix, TLabel>
     luckyRate += sum_along_row_i * sum_along_column_i;
     }
 
-  this->m_OverallAccuracy /= static_cast<double>(m_NumberOfSamples);
-
   this->m_TrueNegativeValues.Fill(m_NumberOfSamples);
   this->m_TrueNegativeValues -= this->m_FalseNegativeValues
                               + this->m_FalsePositiveValues
@@ -116,7 +115,27 @@ ConfusionMatrixMeasurements<TConfusionMatrix, TLabel>
   m_Recalls.Fill(0.);
   m_FScores.Fill(0.);
 
-  const double epsilon = 0.0000000001;
+  if (m_NumberOfSamples > 0)
+    {
+    this->m_OverallAccuracy /= static_cast<double>(m_NumberOfSamples);
+    luckyRate /= vcl_pow(m_NumberOfSamples, 2.0);
+
+    if (vcl_abs(1 - luckyRate) > epsilon)
+      {
+      m_KappaIndex = (m_OverallAccuracy - luckyRate) / (1 - luckyRate);
+      }
+    else
+      {
+      this->m_KappaIndex = 1.;
+      }
+    }
+  else
+    {
+    this->m_OverallAccuracy  = 0.;
+    this->m_KappaIndex = 0.;
+    // no samples, no need to continue
+    return;
+    }
 
   for (unsigned int i = 0; i < m_NumberOfClasses; ++i)
     {
@@ -155,13 +174,6 @@ ConfusionMatrixMeasurements<TConfusionMatrix, TLabel>
       this->m_FScore = 2 * this->m_Recall * this->m_Precision / (this->m_Recall + this->m_Precision);
       }
     }
-
-  luckyRate /= vcl_pow(m_NumberOfSamples, 2.0);
-
-  if (vcl_abs(1 - luckyRate) > epsilon)
-    {
-    m_KappaIndex = (m_OverallAccuracy - luckyRate) / (1 - luckyRate);
-    }
 }
 
 /*
diff --git a/Modules/Radiometry/Simulation/src/otbSailModel.cxx b/Modules/Radiometry/Simulation/src/otbSailModel.cxx
index 76dfd3c08f..2d6b66fae2 100644
--- a/Modules/Radiometry/Simulation/src/otbSailModel.cxx
+++ b/Modules/Radiometry/Simulation/src/otbSailModel.cxx
@@ -337,7 +337,7 @@ SailModel
       // Outputs for the case LAI = 0
       if (m_LAI<0)
       {
-         tss = 1;
+         //tss = 1;
          too = 1;
          tsstoo = 1;
          rdd = 0;
@@ -355,7 +355,7 @@ SailModel
          rdot = rsoil0;
          rsodt = 0;
          rsost = rsoil0;
-         rsot = rsoil0;
+         //rsot = rsoil0;
       }
 
       // Other cases (LAI > 0)
-- 
GitLab