[Gdal-dev] Memory leak related with reference counting

Marek Brudka mbrudka at aster.pl
Fri Jan 7 15:08:12 EST 2005


    GDAL VERSION: 1.25

    AREA/CLASS/EXAMPLE AFFECTED:
      OGR  

    DOES THE PROBLEM AFFECT:
        COMPILATION?
        LINKING?
        EXECUTION? yes
        OTHER (please specify)?

    SYNOPSIS:
It seems OGR uses reference counting inconsistently, what result in 
memory leak.

    DESCRIPTION:
OGR uses reference counting for some object to manage the life cycle of 
objects as well as to decrease OGR memory requirements.
In particular SpatialReferenceSystems are reference counted. While 
reference counting is consistent in OGRProj4CT, namely
OGRSpatialReference are deleted when counter falls below 1, in 
OGRGeometry eg. OGRGeometry::~OGRGeometry and
OGRGeometry::assignSpatialReference a counter is released without 
checking if OGRSpatialReference should be deleted. This may
result in memory leak.
    REPEAT BY:
    Analyze places, where Reference/Dereference method is called.
    SAMPLE FIX/WORKAROUND:
The quick fix is to check if reference counter falls below 1 and 
eventually delete the object eg.

OGRGeometry::~OGRGeometry()
{
    if( poSRS != NULL )
    {
        if ( poSRS->Dereference() <= 0 )
          delete poSRS;
    }
}

However, a better way to manage reference counted objects is to use 
consistently in GDAL intrusive smart pointers.
If the dependency on boost libraries is accepted, then I propose to use 
boost::instrusive_ptr
(http://www.boost.org/libs/smart_ptr/intrusive_ptr.html). If this 
dependency is for some reason undesirable, then a
simple template (boost::instrusive_ptr is 273 lines long) for such 
pointers can be written. I strongly recommend such
technique, as this is simple way to avoid related with reference counted 
memory management.

Regards
Marek Brudka





More information about the Gdal-dev mailing list