Release object into a function - Memory Leak

Asked

Viewed 343 times

1

I am starting in the world Datasnap and I came across a situation that I can not find solution.

My code is on memory Leak, because I can’t release the objects. if I release the objects the access error violated in result.

function TServerMethods1.Teste(Key: string; ID: Integer): TFDJSONDataSets;
var
  Con  : TFDConnection;
  qry  : TFDQuery;
begin

   Con:= TFDConnection.Create(nil);
   qry:= TFDQuery.Create(nil);

    try
      qry.Connection:= Con;

      qry.SQL.Text:= Format('select id, nome from clientes where id = %d', [ID]);
      qry.Open;

      Result:= TFDJSONDataSets.Create;
      TFDJSONDataSetsWriter.ListAdd(Result, qry);

    finally
      FreeAndNil(qry);
      FreeAndNil(Con);
    end;
end;

i need to release the created objects [qry, con] but I’m not getting it.

3 answers

1

The TFDJSONDataSets returns the result of qry which is passed by reference. So you can’t destroy it while the Result not delivered.

How to solve?

vDataSetX := TServerMethods1.Teste('stringX', integerX);
...
  usa o vDataSetX como precisar
...
vDataSetX .Close;
vDataSetX .Free;
vDataSetX  := Nil;

How was passed by reference to the Close, Free will terminate the connection, and the Nil will release from memory the vDataSetX.

  • Thanks for the explanation, I’ll test

  • Junior Moreira, that’s the problem, because Tservermethods1.Testing is on the server, so I would need to release on the server. the way you put it solves the client part, but the server continues with the created object

0

When it comes to Tfdquery, prefer to use . Release instead of .Free. The . Release calls, internally, some routines for data cleaning that Tfdquery calls while processing the request among other operations. If you call only the . Free, you may have memory leaks.

As a rule: See if the object has a Release method and use it. If not, use . Free.

-1

Creating the query and connection with Owner(application) will not need to destroy to prevent leakage.

Or... assign another Wner to be destroyed periodically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.