Debugging with Valgrind
│
English (en) │
!!!WORK IN PROGRESS!!!
Introduction
Valgrind is an instrumentation framework for building dynamic analysis tools. There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. You can read about Valgrind here https://valgrind.org/
A program running under Valgrind is not executed directly by the CPU. Instead it runs on a synthetic CPU provided by Valgrind.
The debugging applications stack is following:
- GDB
- VGDB
- Valgrind executing YourProgram
Though GDB can connect to VGDB directly (process - to - process), Lazarus cannot use this mode. You have to use Remote debugging. In this setup VGDB plays role of GDBServer listening on a TCP port, and Lazarus via GDB connects to it.
So the debugging applications stack with Lazarus will be:
- Lazarus IDE
- GDB
- tcp/ip
- VGDB
- Valgrind executing YourProgram
Usually you will run all parts on same computer. But there is possibility to run them on 2 computers via network.
In the following example everything will be on same computer. Network interface will be localhost and TCP port will be 333333.
Configuration
1- Install valgrind Refer to Valgrind resources to install it.
2- Compile your program with Valgrind option
4- Start Valgrind and VGDB
valgrind --tool=memcheck --leak-check=yes --vgdb-error=0 ./myprogram &
sleep 2; vgdb --port=33333
5- Run your program (with debugger)
Lazarus via VGDB communicates with program in Valgrind. You can set breakpoints, view variable's values like in regular debugger. Also Lasarus will stop on lines where Valgrind throws exceptions. Valgrind tracks memory usage very carefully and issues exceptions where FPC, RTL and memory manager may ignore memory misuse. Like at line 4 below.
mo:=TMyObj.Create;
mo.Field:=12345;
mo.Free;
if mo.Field = 0
then exit;