Reputation: 1336
I have this procedure:
procedure TMainForm.ExtractActor(const actor_id : string);
var
mystream : TStringStream;
js : TlkJSONobject;
begin
mystream:= TStringStream.Create('');
idHTTP1.Get(TIdURI.URLEncode('some dynamic url'),mystream);
js := TlkJSON.ParseText( mystream.DataString ) as TlkJsonObject;
//insert
if UniConnection1.Connected then
begin
UniQuery3.Params[0].Value:= StrToInt(js.getString('id'));
UniQuery3.Open;
if (UniQuery3.RecordCount = 0) then
begin
Uniquery2.Params[0].Value:= StrToInt(js.getString('id'));
Uniquery2.Params[1].Text:= js.getString('name');
Uniquery2.Params[2].Text:= js.getString('locale');
Uniquery2.Params[3].Text:= js.getString('gender');
Uniquery2.Params[4].Text:= js.getString('username');
Uniquery2.Execute;
end;
UniQuery3.Close;
end;
mystream.Free;
end;
Monitoring Windows Task Manager I see that the process memory keeps increasing. After a day or so I will get an Out of Memory error and the application will crash. What am I doing wrong? I'm assuming that neither the JSON or the Devart UniDAC libraries are leaking.
Upvotes: 0
Views: 840
Reputation: 613562
There are a couple of obvious causes for a leak.
The one that is surely a leak is the js
object that you create but fail to destroy. Protect its lifetime with a try
/finally
block:
js := TlkJSON.ParseText( mystream.DataString ) as TlkJsonObject;
try
...
finally
js.Free;
end;
More subtle is the un-protected mystream
. If an exception is raised after mystream
is assigned, and before it is destroyed, you will leak that object. Again you should protect that with a try
/finally
block using the exact same idiom as demonstrated above. The problem with mystream
will only be an issue for you in case your function is raising exceptions. Whilst that might not be the case here you must always protect objects in the manner shown above.
In any event, you should certainly do some leak tracking in your program. There may very well be more leaks. Here are the first steps you need to take:
It is possible that you have leaks during the running of your program, but that are all tidied up when the program closes. These are harder to track and require some extra instrumentation of your program.
Upvotes: 6