-1

I want to show memory leaks in a console app but when using ExitProcess(0) it doesn't show them and without it i don't know how i can quit the app.

This is an example of code that creates a memory leak but doesn't show it:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  sysutils, classes, windows;

function Test: Boolean;
var
   test : TStringList;
begin
  test := TStringList.Create;
  ExitProcess(0);
end;

begin
  try
    ReportMemoryLeaksOnShutdown := true;
    Test;
  except
    on E: Exception do
    begin
      Writeln(E.ClassName, ': ', E.Message);
      REadln;
    end;
  end;
end.

To see the memory leaks I execute the exe from a cmd. Now if I comment ExitProcess I can see them but with it on I can't. Is there a fix for that?

Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
John
  • 261
  • 2
  • 16
  • *I don't know how i can quit the app*. It quits itself, because you have no loop that would keep it running. IOW, as long as there is no exception raised when you create the TStringList, it will exit the console app immediately after that line executes if the ExitProcess call is removed. Your entire app can be distilled down to about 6 or 8 lines of code. – Ken White Apr 03 '18 at 12:41
  • You are exiting the process before the memory manager can display anything, what did you expect? – Sertac Akyuz Apr 03 '18 at 13:19
  • Use "Exit" or "Halt" if you want to exit early. That won't interfere with the memory manager freeing/scanning/reporting memory. – Sertac Akyuz Apr 03 '18 at 13:26
  • @SertacAkyuz The actual application has another function that reads commands. So if i do Exit there it will just exit the function. In the console app you can write different commands that's why i'm using ExitProcess as i can call it from a function and it will close the app itself. Exit just exits the current function. – John Apr 03 '18 at 13:30

1 Answers1

0

ExitProcess exits the calling process. As far as the process is concerned the function does not even return. Hence the memory manager cannot find the chance to scan and report memory leaks.

You have to quit your application using another way. You can use Halt, or raise an exception in the function, or return something from the function that would tell the main program that it would exit.

Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • Cool i made it so a function returns something and i call exit in the main and it shows the memory leaks. Nice. – John Apr 03 '18 at 14:02