Skip to content

Commit b638aa7

Browse files
IgWodalalek
authored andcommitted
Fix a memory leak in the Mat copying constructor
Exception may be rasied inside the body of a copying constructor after refcount has been increased, and beacause in the case of the exception destrcutor is never called what causes memory leak. This commit adds a workaround that calls the release() function before the exception is thrown outside the contructor.
1 parent d25ee8a commit b638aa7

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

modules/core/src/matrix.cpp

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -484,21 +484,31 @@ Mat::Mat(const Mat& m, const Range& _rowRange, const Range& _colRange)
484484
}
485485

486486
*this = m;
487-
if( _rowRange != Range::all() && _rowRange != Range(0,rows) )
487+
try
488488
{
489-
CV_Assert( 0 <= _rowRange.start && _rowRange.start <= _rowRange.end && _rowRange.end <= m.rows );
490-
rows = _rowRange.size();
491-
data += step*_rowRange.start;
492-
flags |= SUBMATRIX_FLAG;
493-
}
489+
if( _rowRange != Range::all() && _rowRange != Range(0,rows) )
490+
{
491+
CV_Assert( 0 <= _rowRange.start && _rowRange.start <= _rowRange.end
492+
&& _rowRange.end <= m.rows );
493+
rows = _rowRange.size();
494+
data += step*_rowRange.start;
495+
flags |= SUBMATRIX_FLAG;
496+
}
494497

495-
if( _colRange != Range::all() && _colRange != Range(0,cols) )
498+
if( _colRange != Range::all() && _colRange != Range(0,cols) )
499+
{
500+
CV_Assert( 0 <= _colRange.start && _colRange.start <= _colRange.end
501+
&& _colRange.end <= m.cols );
502+
cols = _colRange.size();
503+
data += _colRange.start*elemSize();
504+
flags &= cols < m.cols ? ~CONTINUOUS_FLAG : -1;
505+
flags |= SUBMATRIX_FLAG;
506+
}
507+
}
508+
catch(...)
496509
{
497-
CV_Assert( 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols );
498-
cols = _colRange.size();
499-
data += _colRange.start*elemSize();
500-
flags &= cols < m.cols ? ~CONTINUOUS_FLAG : -1;
501-
flags |= SUBMATRIX_FLAG;
510+
release();
511+
throw;
502512
}
503513

504514
if( rows == 1 )

0 commit comments

Comments
 (0)