Skip to content

Commit 37d4e24

Browse files
committed
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 7b861ca commit 37d4e24

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
@@ -279,21 +279,31 @@ Mat::Mat(const Mat& m, const Range& _rowRange, const Range& _colRange) : size(&r
279279
}
280280

281281
*this = m;
282-
if( _rowRange != Range::all() && _rowRange != Range(0,rows) )
282+
try
283283
{
284-
CV_Assert( 0 <= _rowRange.start && _rowRange.start <= _rowRange.end && _rowRange.end <= m.rows );
285-
rows = _rowRange.size();
286-
data += step*_rowRange.start;
287-
flags |= SUBMATRIX_FLAG;
288-
}
284+
if( _rowRange != Range::all() && _rowRange != Range(0,rows) )
285+
{
286+
CV_Assert( 0 <= _rowRange.start && _rowRange.start <= _rowRange.end
287+
&& _rowRange.end <= m.rows );
288+
rows = _rowRange.size();
289+
data += step*_rowRange.start;
290+
flags |= SUBMATRIX_FLAG;
291+
}
289292

290-
if( _colRange != Range::all() && _colRange != Range(0,cols) )
293+
if( _colRange != Range::all() && _colRange != Range(0,cols) )
294+
{
295+
CV_Assert( 0 <= _colRange.start && _colRange.start <= _colRange.end
296+
&& _colRange.end <= m.cols );
297+
cols = _colRange.size();
298+
data += _colRange.start*elemSize();
299+
flags &= cols < m.cols ? ~CONTINUOUS_FLAG : -1;
300+
flags |= SUBMATRIX_FLAG;
301+
}
302+
}
303+
catch(...)
291304
{
292-
CV_Assert( 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols );
293-
cols = _colRange.size();
294-
data += _colRange.start*elemSize();
295-
flags &= cols < m.cols ? ~CONTINUOUS_FLAG : -1;
296-
flags |= SUBMATRIX_FLAG;
305+
release();
306+
throw;
297307
}
298308

299309
if( rows == 1 )

0 commit comments

Comments
 (0)