Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Forms and Tooling

Debugging and Compiler Tools

Debug Pascal with breakpoints and watches, catch range and overflow errors with compiler directives, report memory leaks, and compare Delphi, Free Pascal and Lazarus.

Writing code is half the job. The other half is finding out why it does not do what you meant. Pascal gives you strong help: a compiler that is strict about types, directives that turn on run-time checks, a built-in memory leak report, and an integrated debugger. This lesson shows how to use them, and compares the three tool families you may meet: Delphi, Free Pascal and Lazarus.

Compilers and debuggers do not run in the browser, so Pascal listings are read-only. The C program at the end models the leak report so you can see how it works.

Delphi, Free Pascal, Lazarus

Delphi Free Pascal (FPC) Lazarus
What commercial compiler and IDE from Embarcadero free, open-source compiler free IDE built around FPC
Platforms Windows, macOS, iOS, Android, Linux many, including ARM and embedded Windows, Linux, macOS
UI library VCL (Windows), FMX (cross-platform) none by itself LCL (similar to the VCL)
Default mode Delphi dialect fpc mode; {$mode delphi} or {$mode objfpc} for classes uses objfpc mode
Command line dcc32, dcc64, or MSBuild fpc main.pas lazbuild

Most of this course applies to both languages. When code differs, the usual switch is the mode directive at the top of an FPC unit: {$mode delphi} accepts most Delphi code unchanged. Delphi also offers a free Community Edition for learners and small businesses, subject to Embarcadero's licence terms at the time you download it.

Compiler messages

The compiler reports three kinds of message, and you should clear all of them:

  • Errors stop the build, such as E2003 Undeclared identifier: 'Foo'.
  • Warnings point at likely bugs: W1036 Variable 'X' might not have been initialized. Treat them as errors.
  • Hints report unused variables or parameters (H2164) and similar. They keep a project tidy.

A habit that saves hours: compile after every few lines and fix the first message first. Later errors are often consequences of the first.

Compiler directives

Directives are special comments starting with {$. The ones that matter most while debugging:

Directive Effect
{$R+} range checking: raises ERangeError when an array index is out of bounds
{$Q+} overflow checking: raises EIntOverflow when integer arithmetic overflows
{$I+} / {$I-} I/O checking (see text files)
{$H+} long strings (string = AnsiString/UnicodeString) in FPC
{$IFDEF DEBUG} ... {$ENDIF} include code only for a build with that symbol defined
{$DEFINE X} / {$UNDEF X} define or remove a symbol
{$I filename} include another file

Range and overflow checks are normally off in release builds for speed, and on in the Debug configuration. Always develop with them on. With checks off, A[10] on a five-element array silently reads another variable's memory:

PASCAL
{$R+}
var
  A: array[1..5] of Integer;
  I: Integer;
begin
  for I := 1 to 6 do       // off by one
    A[I] := I * I;          // ERangeError raised at I = 6, not silent corruption
end.

Conditional compilation lets one source serve several targets:

PASCAL
{$IFDEF MSWINDOWS}
  uses Winapi.Windows;
{$ENDIF}
{$IFDEF DEBUG}
  procedure Trace(const Msg: string);
  begin
    OutputDebugString(PChar(Msg));
  end;
{$ELSE}
  procedure Trace(const Msg: string); inline;
  begin
  end;
{$ENDIF}

Predefined symbols include MSWINDOWS, LINUX, MACOS, ANDROID, CPUX64, DEBUG (in the default Debug configuration), and FPC or VER360-style symbols that tell you the compiler version. Beware of piling up $IFDEFs: they are hard to read and test.

The debugger

In the IDE, the everyday loop is:

  1. Set a breakpoint by clicking in the gutter next to a line (F5). The program stops there when it reaches it.
  2. Run with F9. When it stops, the line is highlighted.
  3. Inspect. Hover over a variable, open the Local Variables window, or add a Watch (Ctrl+F5) for an expression such as Count * 2.
  4. Step: F8 steps over a line (run a call as one step), F7 steps into a call, Shift+F8 runs until the current routine returns.
  5. Evaluate/Modify (Ctrl+F7) to try an expression or change a variable's value while stopped.
  6. Call stack (Ctrl+Alt+S) shows how you got here. Click a frame to see its variables.

Useful advanced tools: conditional breakpoints (stop only when I = 999), breakpoint actions (log a message and continue, with no code change), and exception breakpoints. By default Delphi stops when any exception is raised, even ones that your try..except would handle; use the exception options to ignore specific classes once you know they are expected.

A debugger shows what is. To understand why, form a hypothesis: "I think Total is wrong after the third item". Put a breakpoint there, check, and refine. Printing is fine too: OutputDebugString (Windows) shows messages in the Event Log window, and WriteLn works in console applications.

Finding memory leaks

A leak is an object that was created and never freed. Delphi's memory manager can tell you at shutdown. Add one line to the project file:

PASCAL
begin
  ReportMemoryLeaksOnShutdown := True;
  Application.Initialize;
  // ...
end.

When the program exits with unfreed objects, a dialog lists them by class and count, such as TCustomer x 3. The usual causes:

  • no try..finally around a create/free pair,
  • an object held in a list that does not own its objects (use TObjectList or call Free yourself),
  • a missing Free on a field in the destructor,
  • a form or component created with Create(nil).

Free Pascal has the -gh compiler option (the "heaptrc" unit), which prints a similar report with call stacks.

Defensive tools in code

  • Assert(Count >= 0, 'Count must not be negative'); raises EAssertionFailed when the condition is false (disabled by {$C-} in release builds).
  • Use Exception.RaiseOuterException or log E.StackTrace (with a stack-trace library such as JclDebug or madExcept) to see crash locations in production.
  • Write small unit tests with DUnitX (Delphi) or FPCUnit (Free Pascal) for logic that does not need a window.

A leak report in C

The program below wraps malloc and free with counters and prints a leak report at the end, the same idea as ReportMemoryLeaksOnShutdown. One object is deliberately forgotten.

C Stand-in: counting allocations to find a leak

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A debugging checklist

  1. Read the first error or warning, not the last.
  2. Reproduce the bug reliably, then shrink the example.
  3. Turn on {$R+}, {$Q+} and Assert.
  4. Use ReportMemoryLeaksOnShutdown in every project.
  5. Form a hypothesis and test it with a breakpoint or a log line.
  6. After the fix, add a test so the bug cannot return.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which directive makes an out-of-range array index raise an exception?

    {$R+} turns on range checking (ERangeError). {$Q+} is overflow checking.
  2. 2. What does F8 do in the debugger?

    F8 is step over; F7 steps into routines.
  3. 3. A leak report at shutdown says TOrder x 5. What does that mean?

    The report lists objects that were still allocated when the program ended.
  4. 4. Which tool is free and built around the Free Pascal compiler?

    Lazarus is the open-source IDE for Free Pascal, with the LCL component library.

Summary

  • Delphi, Free Pascal and Lazarus share the language; they differ in IDE, platforms and UI library.
  • Fix compiler errors in order, and treat warnings as errors.
  • Develop with range checking ({$R+}), overflow checking ({$Q+}) and Assert on.
  • Use breakpoints, watches, step over/into and the call stack; add conditional breakpoints for loops.
  • Set ReportMemoryLeaksOnShutdown := True to catch unfreed objects.

Next: Project: Contact Book