I have a delphi function that returns a TStringList, but when I return a value and try to use it I get a Access Violation Error i.e
myStringList := FuncStringList(); myStringList.Items.Count // <-- This causes an access violation // function FuncStringList function FuncStringList:TStringList; var vStrList:TStringList; begin vStrList := TStringList.Create; ... // Fill the vStrList Result := vStrList vStrList.Free; //<- when i free here, this function will cause AccessViolation end;
How can I return the TStringList and still free it in the local function?
As Smasher said, you can’t free it; the code calling the function that returns the object is responsible for destroying it.
This is bad code design, by the way, as it makes it confusing as to who allocates and frees. A much better way to do it would be to have the caller create the object and pass it in to the function. That way, the code that creates it also frees it. Something like this:
Now there’s no confusion over who does what – the same code that creates the object is responsible for freeing it. And the code, IMO, is much clearer to read and maintain.