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 := FuncStringLis
How can i return the TStringList and still free it in the local function?
You can't. If you free it in the local function, you can't use the return value. Result and vStrList point to the same TStringList object in memory. TStringList is a class and
Result := vStrList
does therefore not copy the string list, but only copies the reference.
So, instead you should free the string list in the calling context after you're done working with it or pass the string list as a parameter to your function like this
procedure FuncStringList (StringList : TStringList);
and let the calling code create and free the string list. As pointed out by the other answers, this is the preferable way, since it makes ownership very clear.