Sign in Join
Wiki copytemporary

heaptrc: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: heaptrc

OldNewLine
1+**`Heaptrc`** is a unit that can be used to debug allocation and deallocation of memory blocks. It keeps track of calls to [`GetMem`](https://www.freepascal.org/docs-html/rtl/system/getmem.html)/[`FreeMem`](https://www.freepascal.org/docs-html/rtl/system/freemem.html) calls, and, implicitly, of [`New`](https://www.freepascal.org/docs-html/rtl/system/new.html)/[`Dispose`](https://www.freepascal.org/docs-html/rtl/system/dispose.html) statements.
2+
3+> **Warning:**
4+
5+When a program using Heaptrc ends, Heaptrc can write out the total memory used and a list of allocated but not freed blocks to a file. When run in the console (*nix or Windows), Heaptrc will print this output to screen unless otherwise instructed. In Lazarus GUI programs on Windows, the output will appear in numerous small dialog boxes, which may be very unpractical, although you can redirect output to file.
6+
7+![](/wiki-images/7/79/Win_heaptrc_output_no_error.png)
8+
9+On *nix (including BSD, Linux and macOS), by default, nothing will be shown for GUI programs. In this case, to see heaptrc output when you terminate your program (GUI or non-GUI), open "Console In/Output" (Ctrl+Alt+O or View -\> Debug Window -\> ...)
10+
11+See [[leakview]] for details on how to make use of Heaptrc effectively.
12+
13+## Usage
14+
15+### Using Heaptrc in FPC
16+
17+Add a parameter `-gh` to your compilation command line or to `fpc.cfg`.
18+
19+``` bash
20+fpc -gh Helloworld.pas
21+```
22+
23+or usually combined with line info:
24+
25+``` bash
26+fpc -glh Helloworld.pas
27+```
28+
29+This will add Heaptrc implicitly as a hidden first unit of the program's uses clause.
30+
31+> **Warning:** All examples given on this page can only be used in the **main project file**. That is, in a file that begins with `Program ...`, and not `Unit ...`.
32+
33+> **Warning:** Don't confuse using {\$if declared(UseHeapTrace)
34+
35+with using `{$if defined(UseHeapTrace)}}` or `{$ifdef UseHeapTrace}}`. To check heaptrc you need the first option since the others will always be false. }}
36+
37+You can test in code if Heaptrc is active by examining the global constant [**`UseHeapTrace`**](https://www.freepascal.org/docs-html/rtl/heaptrc/useheaptrace.html) for the presence of Heaptrc and its status like so:
38+
39+``` pascal
40+program PossiblyHeaptraced(Input, Output, StdErr);
41+begin
42+ {$if declared(UseHeapTrace)}
43+ WriteLn('Heaptrc is used.');
44+ // Heaptrc reports can be turned off when linked in... so true or false
45+ WriteLn('Heaptrc is active: ', UseHeapTrace);
46+ // you can subsequently test/set any Heaptrc reporting options
47+ {$else}
48+ WriteLn('No trace of Heaptrc.');
49+ {$endIf}
50+end.
51+```
52+
53+### Using Heaptrc in Lazarus
54+
55+To enable this in your Lazarus project:
56+
57+1. Go to *Project Options/Linking* and
58+2. in the Debugging section enable *Use Heaptrc unit (check for mem-leaks) (-gh)*
59+
60+You can test for the presence of `Heaptrc` in a similar manner as in the above example by testing for the presence of `UseHeapTrace` in your Project.lpr file.
61+
62+``` pascal
63+{$if declared(UseHeapTrace)}
64+// ... do something
65+
66+// test if active
67+if UseHeapTrace then
68+begin
69+ // ...
70+end;
71+{$endIf}
72+```
73+
74+### Show report only on leak
75+
76+If you want to show `Heaptrc` report dialog only if there were leaks in your application, then put this [[Becomes|assignment]] somewhere in your main project source file:
77+
78+``` pascal
79+{$if declared(UseHeapTrace)}
80+GlobalSkipIfNoLeaks := True; // supported as of debugger version 3.2.0
81+{$endIf}
82+```
83+
84+### Programmatically disable report
85+
86+If the `UseHeapTrace` variable is `false` when the program exits, then the leak will not be reported, even if it is detected. You can use this in your code:
87+
88+``` pascal
89+UseHeapTrace := false;
90+```
91+
92+Note that changing `UseHeapTrace` can neither turn heaptrc on nor off, since the memory manager cannot be changed while the program is running. This only controls the output of the leak message at the end of the program.
93+
94+This is worth considering, for example, when using [`KeepReleased`](https://www.freepascal.org/docs-html/rtl/heaptrc/keepreleased.html) - this requires a lot of additional memory, and setting `UseHeapTrace := false` will not free it.
95+
96+### Continue execution even on heap error
97+
98+If you want your application to continue execution even in case of a heap error then manipulate [`HaltOnError` constant](https://www.freepascal.org/docs-html/rtl/heaptrc/haltonerror.html) at program startup:
99+
100+``` pascal
101+HaltOnError := False;
102+```
103+
104+### Redirect report to file
105+
106+If you want to redirect leak report to file then add this to beginning of you main project file:
107+
108+``` pascal
109+SetHeapTraceOutput('Trace.log'); // supported as of debugger version 3.2.0
110+```
111+
112+### Why Heaptrc should not be added to the uses clause manually
113+
114+You should never add Heaptrc manually in a normal program, because the Heaptrc unit needs to be loaded before Lineinfo for debugging to work properly.
115+
116+Decoding dwarf debugging info efficiently requires a working heap manager and this means that Heaptrc needs to be loaded before the the [[DWARF]] line info decoding unit which is loaded by -gl, so Heaptrc cannot be used explicitly.
117+
118+Only the compiler itself can insert the unit in its proper place as a hidden first unit in the uses clause. Adding the unit by hand can cause all kind of unwanted side effects. E.g. crashes, reported Lineinfo is not reliable and not all leaks can reliably be reported.
119+
120+This has always been the case, but is only properly documented from FPC version 3.0.2. So if you still see Heaptrc in your uses clause, remove it! for debugging and reporting to work properly.
121+
122+> **Note:** If your program is designed to use an alternative memory manager, you can adapt your program's uses clause like so:
123+>
124+> ``` pascal
125+> program AlternativeMemoryManager(Input, Output, StdErr);
126+> {$mode ObjFPC}
127+> uses
128+> // This will conditionally switch in a memory manager
129+> // based on the presence of Heaptrc
130+> {$if not declared(UseHeapTrace)}
131+> CMem,
132+> {$endIf}
133+> SysUtils, Classes; // the latter two are just to test.
134+>
135+> begin
136+> {$if declared(UseHeapTrace)}
137+> WriteLn('Heaptrc is used.', ' Heaptrc is active: ', UseHeapTrace);
138+> {$else}
139+> WriteLn('No trace of Heaptrc.');
140+> {$endIf}
141+> end.
142+> ```
143+>
144+> In the above example the conditional in the uses clause makes sure that the CMem memory manager is only compiled in if the Heaptrc option is not used.
145+
146+## See also
147+
148+- [Documentation issue 30637](https://gitlab.com/freepascal.org/fpc/documentation/-/issues/30637)
149+- [[leakview]]: Examples how to enable Heaptrc in Lazarus and Free Pascal.
150+- [[doc:rtl/heaptrc/|RTL Reference for unit 'Heaptrc']] (this link is not yet up-to-date)
151+
152+---
153+*From the Free Pascal wiki, page "heaptrc", as it stood on 2024-04-12 after a change by N7800, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history