I have a method which loads OGRFeature
's and extracts data from them.
However, when I call the method OGRFeature::DestroyFeature()
to release the memory, I get a segmentation fault.
void Class::processFeatures() {
OGRFeature* feature;
feature = layer->GetNextFeature();
while( feature != NULL ) {
handleGeometries(); //Handling Geometries
doY(); //Handling Fields
OGRFeature::DestroyFeature(feature);
feature = layer->GetNextFeature();
}
}
void Class::handleGeometries() {
OGRGeometry* geometry = feature->GetGeometryRef();
//Some handling code
delete geometry;
}
The code runs and saves the information if I exclude the DestroyFeature
. This example does work.
#include "gdal.h"
#include "gdal_priv.h"
#include <ogrsf_frmts.h>
int main()
{
GDALAllRegister();
GDALDataset* map;
map = (GDALDataset*) GDALOpenEx("shape.shp",GDAL_OF_VECTOR,NULL,NULL,NULL);
if (map)
{
OGRLayer* layer = map->GetLayer(0);
OGRFeature* feature;
feature = layer->GetNextFeature();
while( feature != NULL ) {
OGRFeature::DestroyFeature(feature);
feature = layer->GetNextFeature();
}
GDALClose(map);
}
return 0;
}
What is causing the problem? And how would I solve it?
EDIT: second example expanded
This answer comes after a series of comments/edits to the original question that lead to this conclusion:
Deleting the geometry pointer in the handleGeoemtry() method is what causes the memory violation when the DestroyFeature()
function is called, as the geometry OGRFeature::GetGeometryRef()
returns a reference to an object but does not transfer the ownership to the caller.
You can use the OGRFeature::StealGeoemtry
to take the ownership, or simply remove the delete geometry
instruction as the DestroyFeature()
function will dispose of it anyway.