A whole day hunting for whoever was changing my data

Created: March 14, 2002 Updated: Sept. 29, 2026

I spent the whole day today looking for whatever was changing my variable, and there wasn't a single place in the code that did it.

I write tools in Delphi for selecting and processing samples. This morning one of the variables started holding values that simply couldn't be there. I checked every assignment, every place it gets passed on, and nothing, according to the code nobody touches it.

It ended with stepping through the program line by line in the debugger, watching that one variable. By evening I caught the moment it changed, except the line being executed had nothing to do with it, it was writing to a completely different array.

It turned out range checking was switched off in the project and one array was being written one element too far. Delphi doesn't check that, so the write simply went into the memory right after the array, and that's exactly where my variable was sitting.

delphi
{$R-}  // range checking off
var
  Counts: array[1..10] of Integer;
  Total: Integer;
  I: Integer;
begin
  Total := 42;
  for I := 1 to 11 do  // one too far, Counts[11] doesn't exist
    Counts[I] := 0;
  // Total == 0 ?!
end;

The fix is a single number, finding it took the whole day.

From now on I switch on range and overflow checking ({$R+} and {$Q+}) in test builds. The program runs a little slower, but a bug like this blows up right where it happens, not somewhere further on. And if a value starts changing by itself again, I'll set a breakpoint on that memory location straight away instead of searching the code.

Update 2026

In Python or Go writing past the end of an array fails immediately, so this particular problem is gone. But the habit from that day stayed with me: don't trust the assumption that data only changes where you can see it in the code.

#delphi #debugowanie

Machine-translated from Polish (original).