Search code examples
segmentation-faultpascalfreelazarusfreepascal

Free Pascal: SIGSEGV error when freeing objects


my Pascal program is supposed to store JSON data from a JSON object into a file but when freeing sub-objects I get a SIGSEGV error.

The file is actually saved correctly as the respective object is freed afterwards.

Here's my code:

...
var  dateiInhalt: TStringlist; jsondaten: string; 
     jsondatenobj,ebenejsondatensubobj,
     sekundaerebenejsondatensubobj,
     gjsonsubobj,hjsonsubobj,
     ijsonsubobj: TJSONObject;

...

dateiInhalt := TStringlist.Create;
jsondatenobj := TJSONObject.Create;
ebenejsondatensubobj := TJSONObject.Create;
sekundaerebenejsondatensubobj := TJSONObject.Create;
gjsonsubobj := TJSONObject.Create;
hjsonsubobj := TJSONObject.Create;
ijsonsubobj := TJSONObject.Create;

ebenejsondatensubobj.Add('vector',TJSONArray.Create(['x','y','z']));
jsondatenobj.Add('ebene',ebenejsondatensubobj); // add subobject (does work)

sekundaerebenejsondatensubobj.Add('vector',TJSONArray.Create(['x','y','z']));
jsondatenobj.Add('sekundaerebene',sekundaerebenejsondatensubobj); 

gjsonsubobj.Add('vector',TJSONArray.Create(['x','y','z']));
jsondatenobj.Add('g',gjsonsubobj);

jsondatenobj.Add('distance','5cm');

dateiInhalt.Add(jsondatenobj.AsJSON); // does work

ebenejsondatensubobj.Free; // no error for those freed objects
sekundaerebenejsondatensubobj.Free;
ijsonsubobj.Free;
hjsonsubobj.Free;
gjsonsubobj.Free;

dateiInhalt.SaveToFile(SaveDlgMain.FileName); // does work correctly
Application.MessageBox('File saved successfully','Saved', MB_ICONINFORMATION);

jsondatenobj.Free; // SIGSEGV appears here
showMessage('test');
dateiInhalt.Free;

...

I already tried changing the order of the .free commands but there was always a SIGSEGV at some point.

What should I do?

Thanks in advance!


Solution

  • Don't free the objects that you already pass to other objects. E.g.

           jsondatenobj.Add('g',gjsonsubobj);
    

    Adds gjsonsuobj to jsondatenobj, so when freeing jsondateobj, gjsonsuobj is freed too.

    If you run this in valgrind, you'd probably get some double free.