Recent

Author Topic: Memory leak with pair GetMem(P, 0) FreeMem(P, 0)  (Read 2454 times)

Thaddy

  • Hero Member
  • *****
  • Posts: 19272
  • Glad to be alive.
Re: Memory leak with pair GetMem(P, 0) FreeMem(P, 0)
« Reply #15 on: July 24, 2023, 02:06:40 pm »
Fixed in fpc trunk.
https://gitlab.com/freepascal.org/fpc/source/-/commit/fb5b891c45a0774f0429eb672402bf760a61fb9a

Bart
I would call it "kludged in trunk" because it simply ignores the purpose of the routine: control size.
objects are fine constructs. You can even initialize them with constructors.

Warfley

  • Hero Member
  • *****
  • Posts: 2067
Re: Memory leak with pair GetMem(P, 0) FreeMem(P, 0)
« Reply #16 on: July 24, 2023, 02:17:31 pm »
Warfley, GetFPCHeapStatus.CurrHeapUsed is correct for detecting leaks (e.g. in tests), it has nothing to do with reusing etc.
No it's not correct for detecting memory leaks, and I have shown you an examply why it is not:
Code: Pascal  [Select][+][-]
  1. uses
  2.   heaptrc;
  3.      
  4. var
  5.   i: Integer;
  6.   p: PInteger;
  7. begin
  8.   heaptrc.keepreleased := True; // Override reusing behavior
  9.   Write(GetFPCHeapStatus.CurrHeapUsed,' bytes => ');
  10.   for i := 0 to 10000 do
  11.   begin
  12.     new(p);
  13.     dispose(p);
  14.   end;
  15.   WriteLn(GetFPCHeapStatus.CurrHeapUsed);
  16. end.
This code is completely memory leak free. The heap trace output states:
Code: Text  [Select][+][-]
  1. 10001 memory blocks allocated : 40004/80008
  2. 10001 memory blocks freed     : 40004/80008
  3. 0 unfreed memory blocks : 0
  4. True heap size : 2326528 (160 used in System startup)
  5. True free heap : 86144
  6. Should be : 2326368
There is no unfreed memory blocks. This code does not leak any memory

Yet the output from CurrentHeapUsed is:
Code: Text  [Select][+][-]
  1. 160 bytes => 2240384

CurrentHeapUsed is not a metric that is useful for detecting memory leaks, because the memory manager may decide to keep freed memory around for some reason or another. Your way of measuring memory leaks relies on certain assumptions on how the memory manager works. But as the code above shows, these assumptions are not always true.

So instead of using a metric that may work when your assumptions may line up with reality, what you should do instead is use a metric that is designed to do the work you want to do. Again valgrind and heaptrc are specifically built to verify if you have memory leaks or not, while as you can see in the example above, CurrentHeapUsed is not.
« Last Edit: July 24, 2023, 02:19:29 pm by Warfley »

 

TinyPortal © 2005-2018