[gdal-dev] GetSpatialRef, OGRSpatialReference and memory leaks ?

Even Rouault even.rouault at spatialys.com
Mon Aug 3 03:01:45 PDT 2020


On samedi 1 août 2020 10:44:45 CEST Andrew C Aitchison wrote:
> I would like to define GetSpatialRef() for my raster driver as something
> like:
> 
>      const OGRSpatialReference* GetSpatialRef() const override {
>          OGRSpatialReference* poSRS = new OGRSpatialReference();
>          if (poSRS->importFromEPSGA(27700)!=OGRERR_NONE)
>          {
>              delete poSRS;
>              poSRS = nullptr;
>          }
>          return poSRS;
>      }
> 
> Unfortunately, valgrid reports that this leaks in the "new"
> on the line
>     OGRSpatialReference* poSRS = new OGRSpatialReference();
> 
> On the other hand,
> 
>      const OGRSpatialReference* GetSpatialRef() const override {
>          return new OGRSpatialReference("EPSG:27700");
>      }

Andrew,

You should hold a OGRSpatialReference object as a member variable of the dataset object 
and return its address. The ownership of the object remains to the dataset object as 
indicated in the doc:


/**
 * \brief Fetch the spatial reference for this dataset.
 *
 * Same as the C function GDALGetSpatialRef().
 *
 * When a projection definition is not available, null is returned
 *
 * @since GDAL 3.0
 *
 * @return a pointer to an internal object. It should not be altered or freed.
 * Its lifetime will be the one of the dataset object, or until the next
 * call to this method.
 *
 * @see http://www.gdal.org/osr_tutorial.html
 */


Even

-- 
Spatialys - Geospatial professional services
http://www.spatialys.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/gdal-dev/attachments/20200803/c150aad2/attachment.html>


More information about the gdal-dev mailing list