What is the best way to clear your memory when using Lkjson in Delphi?

Asked

Viewed 475 times

1

I’m having trouble wiping the memory data when I use Lkjson in Delphi.

I tested using Freeandnil, Free, Destroy and Freeinstance. In some cases I get the following message when closing the application.

An Unexpected memory Leak has occurred. The Unexpected small block Leaks are:

1 - 12 bytes: Tjsonlist x 1

13 - 20 bytes: Tlist x 1

My code is this:;

var
  jlRetorno: TJSONList;
  joPessoa: TJSONObject;
  jlistaDetalhes: TJSONList;
  joDetalhe: TJSONObject;

function BuscarDetalhe(IdPessoa: Integer): Boolean;
begin
    with TFDQuery.Create(nil) do
    try 
        //...SQL
        Open;

        jlistaDetalhes := TJSONList.Create;

        Result := not IsEmpty;

        while not Eof do
        begin
            joDetalhe := TJSONObject.Create;

            joDetalhe.Add('tipo',   FieldByName('tipo').AsString);
            joDetalhe.Add('numero', FieldByName('numero').AsString);

            jlistaDetalhes.Add(joDetalhe);

            Next;
        end;
    finally
        Free;
    end;
end;
begin
with qryConsulta do 
try 
    //...SQL
    jlRetorno := TJSONList.Create;

    while not qryConsulta.Eof do
    begin
        joPessoa := TJSONObject.Create;

        with joPessoa do
        begin
            Add('id',   FieldByName('id').AsInteger);
            Add('nome', FieldByName('nome').AsString);
            Add('cpf',  FieldByName('cpf').AsString);

            if BuscarDetalhe(FieldByName('id').AsInteger) then
                Add('detalhes', jlistaDetalhes);
        end;

        jlRetorno.Add(joPessoa);

        Next;
    end;
    Result := ConverterJsonParaString(jlRetorno);
finally
    FreeAndNil(jlRetorno);
end;
end;

In this case, I have problems because I add other objects within lists and lists within objects. When I create a simple object and just call Free, I have no problems. I believe I have to finish one by one in sequence or first delete the lists from within the child objects.

1 answer

0


I ended up finding a problem in my code.

There was a line where when there was no record in the database, the object was created and was not linked to the parent object, consequently it could not be destroyed when calling the FreeAndNil in the finally

Before:

 jlistaDetalhes := TJSONList.Create;

Afterward:

 if not IsEmpty then
      jlistaDetalhes := TJSONList.Create;

So now just destroy the parent object

FreeAndNil(jlRetorno);

Browser other questions tagged

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