Question

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.

Was it helpful?

Solution

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:

  1. Change your code so that it uses the full version of FastMM.
  2. Set up the FastMM configuration file for full debug. That may involve editing the .inc file and if you find that too daunting, you can use the GUI utility from here: http://jed-software.com/blog/?p=606
  3. Run your program for a little while and then close it. If you have leaks these should be reported at this point.
  4. Fix all your leaks.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top