pythonosgeo

Segmentation Fault (segfault) when using OGR CreateField() in Python


Receiving a segfault when running this very short script in Ubuntu.

from osgeo import ogr, osr

shpfile = 'Census_County_TIGER00_IN.shp'

def cust_field(field):
    '''cust_field(shpfile, field) creates a field definition, which, by calling cust_field(), can be used to create a field using the CreateField() function.
    cust_field() DOES NOT create a field -- it simply creates a "model" for a field, that can then be called later. It's weird, but that's GDAL/OGR, as far as I can tell.'''
    fieldDefn = ogr.FieldDefn(field, ogr.OFTInteger)
    fieldDefn.SetWidth(14)
    fieldDefn.SetPrecision(6)
    return fieldDefn

ds = ogr.Open(shpfile, 1)
lyr = ds.GetLayerByIndex(0)
field = cust_field("Test")
lyr.CreateField(field)

Everything runs smoothly until that last line, when iPython, normal shell Python and the IDLE command line all dump to a segmentation fault. Is this an error on my end or an issue with the underlying C that I'm not addressing properly?


Solution

  • Is this an error on my end or an issue with the underlying C that I'm not addressing properly?

    It is probably both. GDAL/OGR's bindings do tend to segfault occasionally, when objects go out of scope and are garbage collected. While this is a known bug, it is unlikely to be fixed any time soon.

    Chances are you can find a way to work around this. I can't reproduce this segfault with another shapefile on Windows XP, and the following version of GDAL/OGR:

     >>> gdal.VersionInfo('') 
     'GDAL 1.6.0, released 2008/12/04'
    

    You could try temporarily to refactor the cust_field function into the body of the script like this:

    from osgeo import ogr, osr
    
    shpfile = 'Census_County_TIGER00_IN.shp'
    
    ds = ogr.Open(shpfile, 1)
    lyr = ds.GetLayerByIndex(0)
    fieldDefn = ogr.FieldDefn("Test", ogr.OFTInteger)
    fieldDefn.SetWidth(14)
    fieldDefn.SetPrecision(6)
    
    lyr.CreateField(fieldDefn)
    

    Let me know if this solves your problem.