How to fix memory leak when calling ShowMessage?

Viewed 152

I have code like this:

ShowMessage(Memo1.Lines.GetText);

Delphi is telling me there is a leak caused by that code:

delphi message

I try to fix it by using this code:

var
  Message:string;
begin
  Message := Memo1.Lines.GetText;
  try
    ShowMessage(Message);
  finally
    FreeAndNil(Message)
  end;

it's working somehow, however the program is automatically force-closed after that.

Is there a way to avoid the memory leak in this case?

1 Answers

The TStrings.GetText() method returns a PChar pointer to a dynamically allocated buffer which must be freed with StrDispose(), per the documentation:

Allocates a text buffer and fills it with the value of theĀ Text property.

... The caller is responsible for freeing the returned value using the StrDispose procedure.

You are not freeing that buffer after assigning it to your string variable, hence the memory leak, which has nothing to do with ShowMessage() itself.

To fix that, your code would need to look more like this instead:

var
  Message: PChar;
begin
  Message := Memo1.Lines.GetText;
  try
    ShowMessage(Message);
  finally
    StrDispose(Message);
  end;
end;

A better option is to use the TStrings.Text or TControl.Text property instead of the TStrings.GetText() method. The compiler can manage the allocated memory for you:

var
  Message: string;
begin
  Message := Memo1.Lines.Text;
  // or: Message := Memo1.Text;
  ShowMessage(Message);
end;
Related