Fixed some issues found by static analysis (4th round)
authorMaksim Shabunin <maksim.shabunin@gmail.com>
Thu, 29 Jun 2017 13:40:22 +0000 (16:40 +0300)
committerMaksim Shabunin <maksim.shabunin@gmail.com>
Fri, 30 Jun 2017 09:26:53 +0000 (12:26 +0300)
29 files changed:
modules/calib3d/src/ap3p.h
modules/calib3d/src/epnp.cpp
modules/calib3d/src/upnp.cpp
modules/core/include/opencv2/core/cvstd.hpp
modules/core/src/matrix.cpp
modules/dnn/src/layers/convolution_layer.cpp
modules/dnn/src/layers/eltwise_layer.cpp
modules/dnn/src/layers/fully_connected_layer.cpp
modules/dnn/src/layers/permute_layer.cpp
modules/dnn/src/layers/pooling_layer.cpp
modules/dnn/src/torch/THDiskFile.cpp
modules/features2d/src/brisk.cpp
modules/imgcodecs/src/bitstrm.cpp
modules/imgproc/src/approx.cpp
modules/imgproc/src/color.cpp
modules/imgproc/src/contours.cpp
modules/imgproc/src/convhull.cpp
modules/imgproc/src/drawing.cpp
modules/imgproc/src/emd.cpp
modules/imgproc/src/histogram.cpp
modules/imgproc/src/thresh.cpp
modules/imgproc/src/undistort.cpp
modules/objdetect/include/opencv2/objdetect/objdetect_c.h
modules/objdetect/src/detection_based_tracker.cpp
modules/objdetect/src/haar.cpp
modules/objdetect/src/hog.cpp
modules/photo/src/fast_nlmeans_denoising_invoker_commons.hpp
modules/videoio/src/cap_ffmpeg_impl.hpp
modules/videoio/src/cap_mjpeg_decoder.cpp

index 241e3e6..df44198 100644 (file)
@@ -33,7 +33,7 @@ private:
     double fx, fy, cx, cy;
     double inv_fx, inv_fy, cx_fx, cy_fy;
 public:
-    ap3p() {}
+    ap3p() : fx(0), fy(0), cx(0), cy(0), inv_fx(0), inv_fy(0), cx_fx(0), cy_fy(0) {}
 
     ap3p(double fx, double fy, double cx, double cy);
 
index 55971a3..a173b88 100644 (file)
@@ -525,6 +525,8 @@ void epnp::qr_solve(CvMat * A, CvMat * b, CvMat * X)
 {
   const int nr = A->rows;
   const int nc = A->cols;
+  if (nc <= 0 || nr <= 0)
+      return;
 
   if (max_nr != 0 && max_nr < nr)
   {
index 7074d00..a674df5 100644 (file)
@@ -720,6 +720,8 @@ void upnp::qr_solve(Mat * A, Mat * b, Mat * X)
 {
   const int nr = A->rows;
   const int nc = A->cols;
+  if (nr <= 0 || nc <= 0)
+      return;
 
   if (max_nr != 0 && max_nr < nr)
   {
index d401c89..83d5cdb 100644 (file)
@@ -49,7 +49,6 @@
 #endif
 
 #include "opencv2/core/cvdef.h"
-
 #include <cstddef>
 #include <cstring>
 #include <cctype>
@@ -959,8 +958,9 @@ size_t String::find_last_of(const char* s, size_t pos) const
 inline
 String String::toLowerCase() const
 {
+    if (!cstr_)
+        return String();
     String res(cstr_, len_);
-
     for (size_t i = 0; i < len_; ++i)
         res.cstr_[i] = (char) ::tolower(cstr_[i]);
 
index 09a074b..0e18ad2 100644 (file)
@@ -5699,13 +5699,20 @@ double norm( const SparseMat& src, int normType )
     {
         if( normType == NORM_INF )
             for( i = 0; i < N; i++, ++it )
+            {
+                CV_Assert(it.ptr);
                 result = std::max(result, std::abs((double)it.value<float>()));
+            }
         else if( normType == NORM_L1 )
             for( i = 0; i < N; i++, ++it )
+            {
+                CV_Assert(it.ptr);
                 result += std::abs(it.value<float>());
+            }
         else
             for( i = 0; i < N; i++, ++it )
             {
+                CV_Assert(it.ptr);
                 double v = it.value<float>();
                 result += v*v;
             }
@@ -5714,13 +5721,20 @@ double norm( const SparseMat& src, int normType )
     {
         if( normType == NORM_INF )
             for( i = 0; i < N; i++, ++it )
+            {
+                CV_Assert(it.ptr);
                 result = std::max(result, std::abs(it.value<double>()));
+            }
         else if( normType == NORM_L1 )
             for( i = 0; i < N; i++, ++it )
+            {
+                CV_Assert(it.ptr);
                 result += std::abs(it.value<double>());
+            }
         else
             for( i = 0; i < N; i++, ++it )
             {
+                CV_Assert(it.ptr);
                 double v = it.value<double>();
                 result += v*v;
             }
@@ -5747,6 +5761,7 @@ void minMaxLoc( const SparseMat& src, double* _minval, double* _maxval, int* _mi
         float minval = FLT_MAX, maxval = -FLT_MAX;
         for( i = 0; i < N; i++, ++it )
         {
+            CV_Assert(it.ptr);
             float v = it.value<float>();
             if( v < minval )
             {
@@ -5769,6 +5784,7 @@ void minMaxLoc( const SparseMat& src, double* _minval, double* _maxval, int* _mi
         double minval = DBL_MAX, maxval = -DBL_MAX;
         for( i = 0; i < N; i++, ++it )
         {
+            CV_Assert(it.ptr);
             double v = it.value<double>();
             if( v < minval )
             {
index 50b84f7..f5c782f 100644 (file)
@@ -289,7 +289,7 @@ public:
 
         ParallelConv()
             : input_(0), weights_(0), output_(0), ngroups_(0), nstripes_(0),
-              is1x1_(false), useAVX2(false)
+              biasvec_(0), reluslope_(0), activ_(0), is1x1_(false), useAVX2(false)
         {}
 
         static void run( const Mat& input, Mat& output, const Mat& weights,
index 6998c3e..12069e7 100644 (file)
@@ -120,7 +120,7 @@ public:
         int nstripes;
         const ActivationLayer* activ;
 
-        EltwiseInvoker() {}
+        EltwiseInvoker() : srcs(0), nsrcs(0), dst(0), coeffs(0), op(EltwiseLayer::PROD), nstripes(0), activ(0) {}
 
         static void run(const Mat** srcs, int nsrcs, Mat& dst,
                         const std::vector<int>& coeffs, EltwiseOp op,
index 7adb0e5..071593d 100644 (file)
@@ -119,7 +119,7 @@ public:
     class FullyConnected : public ParallelLoopBody
     {
     public:
-        FullyConnected() {}
+        FullyConnected() : srcMat(0), weights(0), biasMat(0), activ(0), dstMat(0), nstripes(0), useAVX2(false) {}
 
         static void run(const Mat& srcMat, const Mat& weights, const Mat& biasMat,
                         Mat& dstMat, const ActivationLayer* activ, int nstripes)
index c93f3ca..56a2782 100644 (file)
@@ -195,7 +195,7 @@ public:
             parallel_for_(Range(0, nstripes), p, nstripes);
         }
 
-        PermuteInvoker() {}
+        PermuteInvoker() : inp(0), out(0), order(0), nstripes(0) {}
 
         void operator()(const Range& r) const
         {
index 9da793a..ce99552 100644 (file)
@@ -147,7 +147,7 @@ public:
         std::vector<int> ofsbuf;
         int poolingType;
 
-        PoolingInvoker() {}
+        PoolingInvoker() : src(0), dst(0), mask(0), nstripes(0), computeMaxIdx(0), poolingType(PoolingLayer::MAX) {}
 
         static void run(const Mat& src, Mat& dst, Mat& mask, Size kernel,
                         Size stride, Size pad, int poolingType,
@@ -263,8 +263,11 @@ public:
                                 }
                                 v_store(dstData + x0, max_val0);
                                 v_store(dstData + x0 + 4, max_val1);
-                                v_store(dstMaskData + x0, max_idx0);
-                                v_store(dstMaskData + x0 + 4, max_idx1);
+                                if (dstMaskData)
+                                {
+                                    v_store(dstMaskData + x0, max_idx0);
+                                    v_store(dstMaskData + x0 + 4, max_idx1);
+                                }
                                 x0 += 7;
                             }
                             else
@@ -350,7 +353,8 @@ public:
                                     }
 
                                 dstData[x0] = max_val;
-                                dstMaskData[x0] = max_index;
+                                if (dstMaskData)
+                                    dstMaskData[x0] = max_index;
                             }
                             else
                             {
index 75e7d00..5f63ced 100644 (file)
@@ -328,6 +328,8 @@ static long THDiskFile_readLong(THFile *self, int64 *data, long n)
     {
       int big_endian = !THDiskFile_isLittleEndianCPU();
       int32_t *buffer = (int32_t*)THAlloc(8*n);
+      if (!buffer)
+          THError("can not allocate buffer");
       nread = fread__(buffer, 8, n, dfself->handle);
       long i;
       for(i = nread; i > 0; i--)
@@ -389,6 +391,8 @@ static long THDiskFile_readString(THFile *self, const char *format, char **str_)
         total += TBRS_BSZ;
         p = (char*)THRealloc(p, total);
       }
+      if (p == NULL)
+        THError("read error: failed to allocate buffer");
       pos += fread(p+pos, 1, total-pos, dfself->handle);
       if (pos < total) /* eof? */
       {
@@ -502,9 +506,13 @@ THFile *THDiskFile_new(const char *name, const char *mode, int isQuiet)
   }
 
   self = (THDiskFile*)THAlloc(sizeof(THDiskFile));
+  if (!self)
+      THError("cannot allocate memory for self");
 
   self->handle = handle;
   self->name = (char*)THAlloc(strlen(name)+1);
+  if (!self->name)
+      THError("cannot allocate memory for self->name");
   strcpy(self->name, name);
   self->isNativeEncoding = 1;
   self->longSize = 0;
index 389650e..955158d 100644 (file)
@@ -776,6 +776,7 @@ BRISK_Impl::computeDescriptorsAndOrOrientation(InputArray _image, InputArray _ma
     const BriskShortPair* max = shortPairs_ + noShortPairs_;
     for (BriskShortPair* iter = shortPairs_; iter < max; ++iter)
     {
+      CV_Assert(iter->i < points_ && iter->j < points_);
       t1 = *(_values + iter->i);
       t2 = *(_values + iter->j);
       if (t1 > t2)
index fdcbe75..a7e187f 100644 (file)
@@ -337,6 +337,7 @@ WBaseStream::WBaseStream()
 {
     m_start = m_end = m_current = 0;
     m_file = 0;
+    m_block_pos = 0;
     m_block_size = BS_DEF_BLOCK_SIZE;
     m_is_opened = false;
     m_buf = 0;
index ec0db30..0960162 100644 (file)
@@ -83,6 +83,7 @@ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size,
         return cvEndWriteSeq( &writer );
     }
 
+    reader.code = 0;
     cvStartReadChainPoints( chain, &reader );
 
     temp.next = 0;
index 6e554cf..488bdc1 100644 (file)
@@ -4486,7 +4486,7 @@ struct RGB2HSV_b
         {
             int b = src[bidx], g = src[1], r = src[bidx^2];
             int h, s, v = b;
-            int vmin = b, diff;
+            int vmin = b;
             int vr, vg;
 
             CV_CALC_MAX_8U( v, g );
@@ -4494,7 +4494,7 @@ struct RGB2HSV_b
             CV_CALC_MIN_8U( vmin, g );
             CV_CALC_MIN_8U( vmin, r );
 
-            diff = v - vmin;
+            uchar diff = saturate_cast<uchar>(v - vmin);
             vr = v == r ? -1 : 0;
             vg = v == g ? -1 : 0;
 
index e05d1a9..77af291 100644 (file)
@@ -557,12 +557,12 @@ icvFetchContour( schar                  *ptr,
     else
     {
         i3 = i0;
-        CV_Assert(i3 != NULL);
         prev_s = s ^ 4;
 
         /* follow border */
         for( ;; )
         {
+            CV_Assert(i3 != NULL);
             s_end = s;
             s = std::min(s, MAX_SIZE - 1);
 
@@ -652,7 +652,6 @@ icvTraceContour( schar *ptr, int step, schar *stop_ptr, int is_hole )
     while( *i1 == 0 && s != s_end );
 
     i3 = i0;
-    CV_Assert(i3 != NULL);
 
     /* check single pixel domain */
     if( s != s_end )
@@ -660,6 +659,7 @@ icvTraceContour( schar *ptr, int step, schar *stop_ptr, int is_hole )
         /* follow border */
         for( ;; )
         {
+            CV_Assert(i3 != NULL);
 
             s = std::min(s, MAX_SIZE - 1);
             while( s < MAX_SIZE - 1 )
@@ -739,12 +739,14 @@ icvFetchContourEx( schar*               ptr,
         /* follow border */
         for( ;; )
         {
+            CV_Assert(i3 != NULL);
             s_end = s;
             s = std::min(s, MAX_SIZE - 1);
 
             while( s < MAX_SIZE - 1 )
             {
                 i4 = i3 + deltas[++s];
+                CV_Assert(i4 != NULL);
                 if( *i4 != 0 )
                     break;
             }
@@ -815,6 +817,7 @@ icvFetchContourEx( schar*               ptr,
 static int
 icvTraceContour_32s( int *ptr, int step, int *stop_ptr, int is_hole )
 {
+    CV_Assert(ptr != NULL);
     int deltas[MAX_SIZE];
     int *i0 = ptr, *i1, *i3, *i4 = NULL;
     int s, s_end;
@@ -844,12 +847,14 @@ icvTraceContour_32s( int *ptr, int step, int *stop_ptr, int is_hole )
         /* follow border */
         for( ;; )
         {
+            CV_Assert(i3 != NULL);
             s_end = s;
             s = std::min(s, MAX_SIZE - 1);
 
             while( s < MAX_SIZE - 1 )
             {
                 i4 = i3 + deltas[++s];
+                CV_Assert(i4 != NULL);
                 if( (*i4 & value_mask) == ccomp_val )
                     break;
             }
@@ -873,6 +878,7 @@ icvFetchContourEx_32s( int*                 ptr,
                        int                  _method,
                        CvRect*              _rect )
 {
+    CV_Assert(ptr != NULL);
     int         deltas[MAX_SIZE];
     CvSeqWriter writer;
     int        *i0 = ptr, *i1, *i3, *i4;
@@ -926,11 +932,13 @@ icvFetchContourEx_32s( int*                 ptr,
         /* follow border */
         for( ;; )
         {
+            CV_Assert(i3 != NULL);
             s_end = s;
 
             do
             {
                 i4 = i3 + deltas[++s];
+                CV_Assert(i4 != NULL);
             }
             while( (*i4 & value_mask) != ccomp_val && ( s < MAX_SIZE - 1 ) );
             s &= 7;
index 1f8ef7b..c3287b8 100644 (file)
@@ -584,7 +584,7 @@ CV_IMPL CvSeq* cvConvexityDefects( const CvArr* array,
 
         hull = cvMakeSeqHeaderForArray(
                                        CV_SEQ_KIND_CURVE|CV_MAT_TYPE(mat->type)|CV_SEQ_FLAG_CLOSED,
-                                       sizeof(CvContour), CV_ELEM_SIZE(mat->type), mat->data.ptr,
+                                       sizeof(hull_header), CV_ELEM_SIZE(mat->type), mat->data.ptr,
                                        mat->cols + mat->rows - 1, &hull_header, &hullblock );
     }
 
@@ -664,6 +664,7 @@ CV_IMPL CvSeq* cvConvexityDefects( const CvArr* array,
             int t = *(int*)hull_reader.ptr;
             hull_next = CV_GET_SEQ_ELEM( CvPoint, ptseq, t );
         }
+        CV_Assert(hull_next != NULL && hull_cur != NULL);
 
         dx0 = (double)hull_next->x - (double)hull_cur->x;
         dy0 = (double)hull_next->y - (double)hull_cur->y;
index a31a19e..0d1e785 100644 (file)
@@ -2600,6 +2600,7 @@ cvDrawContours( void* _img, CvSeq* contour,
         void* clr = (contour->flags & CV_SEQ_FLAG_HOLE) == 0 ? ext_buf : hole_buf;
 
         cvStartReadSeq( contour, &reader, 0 );
+        CV_Assert(reader.ptr != NULL);
         if( thickness < 0 )
             pts.resize(0);
 
index e5bc695..3b1e4af 100644 (file)
@@ -730,7 +730,7 @@ icvNewSolution( CvEMDState * state )
     int i, j;
     float min_val = CV_EMD_INF;
     int steps;
-    CvNode2D head, *cur_x, *next_x, *leave_x = 0;
+    CvNode2D head = {0, {0}, 0, 0}, *cur_x, *next_x, *leave_x = 0;
     CvNode2D *enter_x = state->enter_x;
     CvNode2D **loop = state->loop;
 
@@ -783,7 +783,7 @@ icvNewSolution( CvEMDState * state )
     while( (next_x = cur_x->next[0]) != leave_x )
     {
         cur_x = next_x;
-        assert( cur_x );
+        CV_Assert( cur_x );
     }
     cur_x->next[0] = next_x->next[0];
     state->rows_x[i] = head.next[0];
@@ -793,7 +793,7 @@ icvNewSolution( CvEMDState * state )
     while( (next_x = cur_x->next[1]) != leave_x )
     {
         cur_x = next_x;
-        assert( cur_x );
+        CV_Assert( cur_x );
     }
     cur_x->next[1] = next_x->next[1];
     state->cols_x[j] = head.next[1];
index 357038b..cdd1086 100644 (file)
@@ -83,7 +83,7 @@ calcHistLookupTables_8u( const Mat& hist, const SparseMat& shist,
             }
         }
     }
-    else
+    else if (ranges)
     {
         for( i = 0; i < dims; i++ )
         {
@@ -111,6 +111,10 @@ calcHistLookupTables_8u( const Mat& hist, const SparseMat& shist,
             }
         }
     }
+    else
+    {
+        CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided");
+    }
 }
 
 
@@ -938,7 +942,7 @@ calcHist_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas,
             }
         }
     }
-    else
+    else if (_ranges)
     {
         // non-uniform histogram
         const float* ranges[CV_MAX_DIM];
@@ -980,6 +984,10 @@ calcHist_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas,
                 ptrs[i] += deltas[i*2 + 1];
         }
     }
+    else
+    {
+        CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided");
+    }
 }
 
 
@@ -1457,8 +1465,10 @@ void cv::calcHist( const Mat* images, int nimages, const int* channels,
     if(histdata != hist.data)
         accumulate = false;
 
-    CV_IPP_RUN(nimages == 1 && dims == 1 && channels && channels[0] == 0 && _mask.empty() && images[0].dims <= 2,
-                ipp_calchist(images[0], hist, histSize[0], ranges, uniform, accumulate));
+    CV_IPP_RUN(
+        nimages == 1 && dims == 1 && channels && channels[0] == 0
+            && _mask.empty() && images[0].dims <= 2 && ranges && ranges[0],
+        ipp_calchist(images[0], hist, histSize[0], ranges, uniform, accumulate));
 
     Mat ihist = hist;
     ihist.flags = (ihist.flags & ~CV_MAT_TYPE_MASK)|CV_32S;
@@ -1537,7 +1547,7 @@ calcSparseHist_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas,
                 ptrs[i] += deltas[i*2 + 1];
         }
     }
-    else
+    else if (_ranges)
     {
         // non-uniform histogram
         const float* ranges[CV_MAX_DIM];
@@ -1577,6 +1587,10 @@ calcSparseHist_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas,
                 ptrs[i] += deltas[i*2 + 1];
         }
     }
+    else
+    {
+        CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided");
+    }
 }
 
 
@@ -1636,6 +1650,7 @@ static void calcHist( const Mat* images, int nimages, const int* channels,
         SparseMatIterator it = hist.begin();
         for( i = 0, N = hist.nzcount(); i < N; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             Cv32suf* val = (Cv32suf*)it.ptr;
             val->i = cvRound(val->f);
         }
@@ -1666,6 +1681,7 @@ static void calcHist( const Mat* images, int nimages, const int* channels,
         SparseMatIterator it = hist.begin();
         for( i = 0, N = hist.nzcount(); i < N; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             Cv32suf* val = (Cv32suf*)it.ptr;
             val->f = (float)val->i;
         }
@@ -1907,7 +1923,7 @@ calcBackProj_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas,
             }
         }
     }
-    else
+    else if (_ranges)
     {
         // non-uniform histogram
         const float* ranges[CV_MAX_DIM];
@@ -1949,6 +1965,10 @@ calcBackProj_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas,
                 ptrs[i] += deltas[i*2 + 1];
         }
     }
+    else
+    {
+        CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided");
+    }
 }
 
 
@@ -2153,7 +2173,7 @@ calcSparseBackProj_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas
                 ptrs[i] += deltas[i*2 + 1];
         }
     }
-    else
+    else if (_ranges)
     {
         // non-uniform histogram
         const float* ranges[CV_MAX_DIM];
@@ -2193,6 +2213,10 @@ calcSparseBackProj_( std::vector<uchar*>& _ptrs, const std::vector<int>& _deltas
                 ptrs[i] += deltas[i*2 + 1];
         }
     }
+    else
+    {
+        CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided");
+    }
 }
 
 
@@ -2260,7 +2284,6 @@ void cv::calcBackProject( const Mat* images, int nimages, const int* channels,
                        dims, hist.hdr->size, ranges,
                        uniform, ptrs, deltas, imsize, uniranges );
     const double* _uniranges = uniform ? &uniranges[0] : 0;
-
     int depth = images[0].depth();
     if( depth == CV_8U )
         calcSparseBackProj_8u(ptrs, deltas, imsize, hist, dims, ranges,
@@ -2702,12 +2725,14 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
         std::swap(PH1, PH2);
 
     SparseMatConstIterator it = PH1->begin();
+
     int N1 = (int)PH1->nzcount(), N2 = (int)PH2->nzcount();
 
     if( (method == CV_COMP_CHISQR) || (method == CV_COMP_CHISQR_ALT) )
     {
         for( i = 0; i < N1; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             float v1 = it.value<float>();
             const SparseMat::Node* node = it.node();
             float v2 = PH2->value<float>(node->idx, (size_t*)&node->hashval);
@@ -2723,6 +2748,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
 
         for( i = 0; i < N1; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             double v1 = it.value<float>();
             const SparseMat::Node* node = it.node();
             s12 += v1*PH2->value<float>(node->idx, (size_t*)&node->hashval);
@@ -2733,6 +2759,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
         it = PH2->begin();
         for( i = 0; i < N2; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             double v2 = it.value<float>();
             s2 += v2;
             s22 += v2*v2;
@@ -2750,6 +2777,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
     {
         for( i = 0; i < N1; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             float v1 = it.value<float>();
             const SparseMat::Node* node = it.node();
             float v2 = PH2->value<float>(node->idx, (size_t*)&node->hashval);
@@ -2763,6 +2791,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
 
         for( i = 0; i < N1; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             double v1 = it.value<float>();
             const SparseMat::Node* node = it.node();
             double v2 = PH2->value<float>(node->idx, (size_t*)&node->hashval);
@@ -2772,7 +2801,10 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
 
         it = PH2->begin();
         for( i = 0; i < N2; i++, ++it )
+        {
+            CV_Assert(it.ptr != NULL);
             s2 += it.value<float>();
+        }
 
         s1 *= s2;
         s1 = fabs(s1) > FLT_EPSILON ? 1./std::sqrt(s1) : 1.;
@@ -2782,6 +2814,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method )
     {
         for( i = 0; i < N1; i++, ++it )
         {
+            CV_Assert(it.ptr != NULL);
             double v1 = it.value<float>();
             const SparseMat::Node* node = it.node();
             double v2 = PH2->value<float>(node->idx, (size_t*)&node->hashval);
@@ -3444,7 +3477,10 @@ cvCalcArrHist( CvArr** img, CvHistogram* hist, int accumulate, const CvArr* mask
         cv::SparseMatConstIterator it = sH.begin();
         int nz = (int)sH.nzcount();
         for( i = 0; i < nz; i++, ++it )
+        {
+            CV_Assert(it.ptr != NULL);
             *(float*)cvPtrND(sparsemat, it.node()->idx, 0, -2) = (float)*(const int*)it.ptr;
+        }
     }
 }
 
index d740b9b..674d12b 100644 (file)
@@ -206,7 +206,7 @@ thresh_8u( const Mat& _src, Mat& _dst, uchar thresh, uchar maxval, int type )
     if( j_scalar < roi.width )
     {
         const int thresh_pivot = thresh + 1;
-        uchar tab[256];
+        uchar tab[256] = {0};
         switch( type )
         {
         case THRESH_BINARY:
index 67bd034..fbce448 100644 (file)
@@ -149,6 +149,14 @@ void cv::initUndistortRectifyMap( InputArray _cameraMatrix, InputArray _distCoef
         double _x = i*ir[1] + ir[2], _y = i*ir[4] + ir[5], _w = i*ir[7] + ir[8];
 
         int j = 0;
+
+        if (m1type == CV_16SC2)
+            CV_Assert(m1 != NULL && m2 != NULL);
+        else if (m1type == CV_32FC1)
+            CV_Assert(m1f != NULL && m2f != NULL);
+        else
+            CV_Assert(m1 != NULL);
+
 #if CV_AVX2
 if( USE_AVX2 )
 {
index b3ee7f4..67dc2f4 100644 (file)
@@ -69,6 +69,7 @@ extern "C" {
     (((const CvHaarClassifierCascade*)(haar))->flags & CV_MAGIC_MASK)==CV_HAAR_MAGIC_VAL)
 
 #define CV_HAAR_FEATURE_MAX  3
+#define CV_HAAR_STAGE_MAX 1000
 
 typedef struct CvHaarFeature
 {
index 88a1ce5..4912948 100644 (file)
@@ -610,7 +610,8 @@ cv::DetectionBasedTracker::DetectionBasedTracker(cv::Ptr<IDetector> mainDetector
             && trackingDetector );
 
     if (mainDetector) {
-        separateDetectionWork.reset(new SeparateDetectionWork(*this, mainDetector, params));
+        Ptr<SeparateDetectionWork> tmp(new SeparateDetectionWork(*this, mainDetector, params));
+        separateDetectionWork.swap(tmp);
     }
 
     weightsPositionsSmoothing.push_back(1);
index c66d4de..cb24479 100644 (file)
@@ -1848,7 +1848,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size )
         sscanf( stage, "%d%n", &count, &dl );
         stage += dl;
 
-        assert( count > 0 );
+        CV_Assert( count > 0 && count < CV_HAAR_STAGE_MAX);
         cascade->stage_classifier[i].count = count;
         cascade->stage_classifier[i].classifier =
             (CvHaarClassifier*)cvAlloc( count*sizeof(cascade->stage_classifier[i].classifier[0]));
@@ -1862,6 +1862,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size )
             sscanf( stage, "%d%n", &classifier->count, &dl );
             stage += dl;
 
+            CV_Assert( classifier->count > 0 && classifier->count< CV_HAAR_STAGE_MAX);
             classifier->haar_feature = (CvHaarFeature*) cvAlloc(
                 classifier->count * ( sizeof( *classifier->haar_feature ) +
                                       sizeof( *classifier->threshold ) +
@@ -1878,7 +1879,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size )
                 sscanf( stage, "%d%n", &rects, &dl );
                 stage += dl;
 
-                assert( rects >= 2 && rects <= CV_HAAR_FEATURE_MAX );
+                CV_DbgAssert( rects >= 2 && rects <= CV_HAAR_FEATURE_MAX );
 
                 for( k = 0; k < rects; k++ )
                 {
@@ -1890,7 +1891,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size )
                     stage += dl;
                     classifier->haar_feature[l].rect[k].r = r;
                 }
-                sscanf( stage, "%s%n", str, &dl );
+                sscanf( stage, "%99s%n", str, &dl );
                 stage += dl;
 
                 classifier->haar_feature[l].tilted = strncmp( str, "tilted", 6 ) == 0;
@@ -1926,6 +1927,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size )
         }
         stage += dl;
 
+        CV_Assert(parent >= 0 && parent < i);
         cascade->stage_classifier[i].parent = parent;
         cascade->stage_classifier[i].next = next;
         cascade->stage_classifier[i].child = -1;
index ed78e3b..ac02e67 100644 (file)
@@ -3694,23 +3694,31 @@ void HOGDescriptor::readALTModel(String modelfile)
         String eerr("version?");
         String efile(__FILE__);
         String efunc(__FUNCTION__);
+        fclose(modelfl);
+
         throw Exception(Error::StsError, eerr, efile, efunc, __LINE__);
     }
     if(strcmp(version_buffer,"V6.01")) {
         String eerr("version doesnot match");
         String efile(__FILE__);
         String efunc(__FUNCTION__);
+        fclose(modelfl);
+
         throw Exception(Error::StsError, eerr, efile, efunc, __LINE__);
     }
     /* read version number */
     int version = 0;
     if (!fread (&version,sizeof(int),1,modelfl))
-    { throw Exception(); }
+    {
+        fclose(modelfl);
+        throw Exception();
+    }
     if (version < 200)
     {
         String eerr("version doesnot match");
         String efile(__FILE__);
         String efunc(__FUNCTION__);
+        fclose(modelfl);
         throw Exception();
     }
     int kernel_type;
@@ -3729,6 +3737,7 @@ void HOGDescriptor::readALTModel(String modelfile)
         nread=fread(&(coef_const),sizeof(double),1,modelfl);
         int l;
         nread=fread(&l,sizeof(int),1,modelfl);
+        CV_Assert(l >= 0 && l < 0xFFFF);
         char* custom = new char[l];
         nread=fread(custom,sizeof(char),l,modelfl);
         delete[] custom;
@@ -3749,11 +3758,13 @@ void HOGDescriptor::readALTModel(String modelfile)
     detector.clear();
     if(kernel_type == 0) { /* linear kernel */
         /* save linear wts also */
+        CV_Assert(totwords + 1 > 0 && totwords < 0xFFFF);
         double *linearwt = new double[totwords+1];
         int length = totwords;
         nread = fread(linearwt, sizeof(double), totwords + 1, modelfl);
         if(nread != static_cast<size_t>(length) + 1) {
             delete [] linearwt;
+            fclose(modelfl);
             throw Exception();
         }
 
@@ -3764,6 +3775,7 @@ void HOGDescriptor::readALTModel(String modelfile)
         setSVMDetector(detector);
         delete [] linearwt;
     } else {
+        fclose(modelfl);
         throw Exception();
     }
     fclose(modelfl);
index d8eb344..d36c85a 100644 (file)
@@ -397,7 +397,7 @@ template <typename ET, typename IT, typename EW> struct incWithWeight_<Vec<ET, 4
 template <typename T, typename IT, typename WT>
 static inline void incWithWeight(IT* estimation, IT* weights_sum, WT weight, T p)
 {
-    return incWithWeight_<T, IT, WT>::f(estimation, weights_sum, weight, p);
+    incWithWeight_<T, IT, WT>::f(estimation, weights_sum, weight, p);
 }
 
 template <typename IT, typename UIT, int nc, int nw> struct divByWeightsSum_
@@ -434,7 +434,7 @@ template <typename IT, typename UIT, int n> struct divByWeightsSum_<IT, UIT, n,
 template <typename IT, typename UIT, int nc, int nw>
 static inline void divByWeightsSum(IT* estimation, IT* weights_sum)
 {
-    return divByWeightsSum_<IT, UIT, nc, nw>::f(estimation, weights_sum);
+    divByWeightsSum_<IT, UIT, nc, nw>::f(estimation, weights_sum);
 }
 
 template <typename T, typename IT> struct saturateCastFromArray_
index afe083e..8e6397b 100644 (file)
@@ -669,13 +669,13 @@ struct ImplMutex::Impl
 
 void ImplMutex::init()
 {
-    impl = (Impl*)malloc(sizeof(Impl));
+    impl = new Impl();
     impl->init();
 }
 void ImplMutex::destroy()
 {
     impl->destroy();
-    free(impl);
+    delete(impl);
     impl = NULL;
 }
 void ImplMutex::lock() { impl->lock(); }
@@ -1387,7 +1387,7 @@ void CvVideoWriter_FFMPEG::init()
 static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bool alloc)
 {
     AVFrame * picture;
-    uint8_t * picture_buf;
+    uint8_t * picture_buf = 0;
     int size;
 
 #if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \
@@ -1416,6 +1416,7 @@ static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bo
     }
     else {
     }
+
     return picture;
 }
 
@@ -1511,6 +1512,8 @@ static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
                 best= p;
             }
         }
+        if (best == NULL)
+            return NULL;
         c->time_base.den= best->num;
         c->time_base.num= best->den;
     }
@@ -1796,24 +1799,27 @@ void CvVideoWriter_FFMPEG::close()
 
     av_free(outbuf);
 
-    if (!(fmt->flags & AVFMT_NOFILE))
+    if (oc)
     {
-        /* close the output file */
+        if (!(fmt->flags & AVFMT_NOFILE))
+        {
+            /* close the output file */
 
 #if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
 #if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
-        url_fclose(oc->pb);
+            url_fclose(oc->pb);
 #else
-        url_fclose(&oc->pb);
+            url_fclose(&oc->pb);
 #endif
 #else
-        avio_close(oc->pb);
+            avio_close(oc->pb);
 #endif
 
-    }
+        }
 
-    /* free the stream */
-    avformat_free_context(oc);
+        /* free the stream */
+        avformat_free_context(oc);
+    }
 
     av_freep(&aligned_input);
 
@@ -2114,6 +2120,8 @@ bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
 CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
 {
     CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
+    if (!capture)
+        return 0;
     capture->init();
     if( capture->open( filename ))
         return capture;
@@ -2158,6 +2166,8 @@ CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int four
                                                   int width, int height, int isColor )
 {
     CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
+    if (!writer)
+        return 0;
     writer->init();
     if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
         return writer;
@@ -2322,6 +2332,8 @@ AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext *oc, CV_CODEC
                 }
             }
 
+            if (best == NULL)
+                return NULL;
             c->time_base.den= best->num;
             c->time_base.num= best->den;
         }
@@ -2463,6 +2475,8 @@ void OutputMediaStream_FFMPEG::write(unsigned char* data, int size, int keyFrame
 struct OutputMediaStream_FFMPEG* create_OutputMediaStream_FFMPEG(const char* fileName, int width, int height, double fps)
 {
     OutputMediaStream_FFMPEG* stream = (OutputMediaStream_FFMPEG*) malloc(sizeof(OutputMediaStream_FFMPEG));
+    if (!stream)
+        return 0;
 
     if (stream->open(fileName, width, height, fps))
         return stream;
@@ -2730,6 +2744,8 @@ bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFi
 InputMediaStream_FFMPEG* create_InputMediaStream_FFMPEG(const char* fileName, int* codec, int* chroma_format, int* width, int* height)
 {
     InputMediaStream_FFMPEG* stream = (InputMediaStream_FFMPEG*) malloc(sizeof(InputMediaStream_FFMPEG));
+    if (!stream)
+        return 0;
 
     if (stream && stream->open(fileName, codec, chroma_format, width, height))
         return stream;
index 2ded72e..b5c5ff9 100644 (file)
@@ -553,6 +553,7 @@ bool AviMjpegStream::parseHdrlList(MjpegInputStream& in_str)
         {
             m_is_indx_present = ((avi_hdr.dwFlags & 0x10) != 0);
             DWORD number_of_streams = avi_hdr.dwStreams;
+            CV_Assert(number_of_streams < 0xFF);
             m_width = avi_hdr.dwWidth;
             m_height = avi_hdr.dwHeight;