[Gdal-dev] Where does the CPLError list get freed?

Frank Warmerdam warmerdam at pobox.com
Wed Oct 11 22:02:12 EDT 2006

Craig Miller wrote:
> I'm on the warpath to get rid of a few niggling memory leaks that I'm
> detecting.  A couple of items have me a bit puzzled at this point and I was
> hoping to get a bit of clarification.
> 1.  If I call CPLGetLastErrorMsg() when there is no error, it obtains a
> CPLErrorContext via CPLGetErrorContext() which creates an empty
> CPLErrorContext and adds it to the list if it doesn't exist.  I've looked a
> fair amount now, but can't seem to locate where this memory gets freed.


It took some digging but I have determined that error contexts are
registered with the CPL TLS (thread local storage) services when
created (via CPLSetTLS()) and the context is marked to be deleted on
cleanup.  That is when CPLCleanupTLS() gets called.  The actual
error buffer is part of the same memory block as the error context so
they get cleaned up together.

CPLCleanupTLS() is called by the GDALDriverManager() cleanup, so it should
be sufficient to call GDALDestroyDriverManager() (and to avoid calling any
CPL services after that).

> 2.  Does CPLErrorReset clobber any szLastErrMsg that may have already been
> assigned?

Yes, it deliberately clears the last error message and code set.

> ----------
> Here is the stack trace showing where the memory is being allocated that
> isn't being freed.
> Call Stack:
>     c:\vault\gdal\port\cpl_vsisimple.cpp (323): VSICalloc
>     c:\vault\gdal\port\cpl_conv.cpp (240): CPLCalloc
>     c:\vault\gdal\port\cpl_error.cpp (122): CPLGetErrorContext
>     c:\vault\gdal\port\cpl_error.cpp (436): CPLGetLastErrorMsg
>     c:\vault\freeworlddesktop\geolib\geodatabase.cpp (53):
> CGeoDatabase::SetConnection
> Line 53 of CGeoDatabase::SetConnection is:
>    const char* errMsg = CPLGetLastErrorMsg();
> CPLErrorReset() is called 2 lines later.
> The documentation for CPLGetLastErrorMsg indicates that the string returned
> should not be freed by the caller.

As mentioned above, calling GDALDestroyDriverManager() on application shutdown
should be sufficient to cleanup the error buffer.

Best regards,
I set the clouds in motion - turn up   | Frank Warmerdam, warmerdam at pobox.com
light and sound - activate the windows | http://pobox.com/~warmerdam
and watch the world go round - Rush    | President OSGeo, http://osgeo.org

More information about the Gdal-dev mailing list