Memory leak in the Win64 Delphi RTL during thread shutdown?

后端 未结 3 1825
抹茶落季
抹茶落季 2021-01-31 02:46

For a long time I’ve noticed that the Win64 version of my server application leak memory. While the Win32 version works fine with a relatively stable memory footprint, the memor

相关标签:
3条回答
  • 2021-01-31 03:22

    In order to avoid the exception memoryleak trap, you could try to put an try/except around the FoobarProc. Maybe not for a definitive solution, but to see why the axception is raised in the first place.

    I usually have something like this:

    try
      FooBarProc()
    except
      if IsFatalException(ExceptObject) then // checks for system exceptions like AV, invalidop etc
        OutputDebugstring(PChar(ExceptionToString(ExceptObject))) // or some other way of logging
    end;
    
    0 讨论(0)
  • 2021-01-31 03:24

    I use Delphi 10.2.3 and the problem described seems to still exist, at least under the following circumstances.

    // Remark: My TFooThread is created within the 64 Bit DLL:
    
    procedure TFooThread.Execute;
    begin
     while not terminated do
      try
       ReadBlockingFromIndySocket();
       ProcessData();
      except on E:Exception do
       begin
        LogTheException(E.Message);
        // Leave loop and thread
        Abort;
       end
      end;
    end;
    

    This leaks memory whenever the loop/thread is left. MadExcept leak report shows that an exception object is not destroyed, in my case mostly an EIdConnClosedGracefully when the connection was closed remotely. The problem was found to be the Abort statement to leave the loop and thus the thread. Indications in the leak report seem to proof the observations of @RemyLebeau. Running the exact same code in the main program instead of the 64 Bit DLL does not leak any memory.

    Solution: Exchange the Abort statement with Exit.

    Conclusion: A thread execution function in a 64 Bit DLL must not be left with an exception (Abort is an exception as well), or else the exception causes a memory leak.

    At least this worked for me.

    0 讨论(0)
  • 2021-01-31 03:28

    A very simple work around is to re-use the thread and not create and destroy them. Threads are pretty expensive, you'll probably get a perf boost too... Kudos on the debugging though...

    0 讨论(0)
提交回复
热议问题