[Insight-developers] Vector::Get_vnl_vector() leaks

Lydia Ng lng@insightful.com
Tue, 24 Jul 2001 18:56:48 -0700


FYI: There some memory leak problems with
Vector::Get_vnl_vector.

--------------------------
Firstly there are two version of of Get_vnl_vector()
one that returns a vnl_vector_ref and one that returns
a vnl_vector

I would expect that for:

vnl_vector<double> bb = aa.Get_vnl_vector();

the vnl_vector version would be called.
But instead vnl_vector_ref version is called both
in VC++ and gcc (Cygwin)!

I don't think this is the desired effect.

---------------------------

In Get_vnl_vector() a vnl_vector_ref is created internally
and returned:

template<class T, unsigned int TVectorDimension>
vnl_vector_ref< T >
Vector<T, TVectorDimension>
::Get_vnl_vector( void )
{
  vnl_vector_ref< T > vector_ref( TVectorDimension,
this->GetDataPointer() );
  return vector_ref;  /* <=== Copy constructor called here */
}

However, a copy constructor is called on the return statement.

Since vnl_vector_ref doesn't have any copy constructors the
vnl_vector(const vnl_vector &)constructor is called instead.
Hence, there is allocation of new memory and element-by-element
copying.

Worst still in the vnl_vector_ref destructor, the data pointer
is set to NULL - because it doesn't want to release memory
it doesn't own!
Thus, the memory allocated by the copy construction
at the return statement is not release
- hence a memory leak.

This seems to occur both on VC++ and gcc (Cygwin).

-----------------------------

Lydia