Nitkov
Nitkov

Reputation: 468

Access violations on string operations in Delphi

I have a Delphi application that reads data form a file and stores it in an array. Each row in a file contains an address, lineTypeIndicator and data. This is the algorithm (contains code that I believe is critical):

AssignFile(inputFile, inFileName);
Reset(inputFile);
  while not EOF(inputFile) do
  begin
    Readln(inputFile,fileLineBuffer);        
     if  Copy(fileLineBuffer, 8, 2) = '01' then  //Never managed to catch the error here
    begin
      break;
    end;

    //extract the address from the line and use it to determine max and min address.
  end;

//Now that you have min and max address, use it to set the length of an char array
SetLength(memoryArray,(lastAddress - firstAddress) * 2);

Reset(inputFile);
  while not EOF(inputFile) do
  begin
    Readln(inputFile,fileLineBuffer);

     if  Copy(fileLineBuffer, 8, 2) = '01' then    //I caught all the errors here
    begin
      break;
    end;

    //extract the address and data from the fileLineBuffer and place it in the corresponding place in an array
  end;

This code is executed every time the user clicks the corresponding button on a form. It runs the first few times it is executed, but then after a few runs i get this:

MyProgram.exe faulted with message: 'access violation at 0x00406111: write of address 0x00090d1c (this varies). Proceess stopped. Use step or run to continue.

To me, this smells like some kind of heap overflow. I have tried replacing

if  Copy(fileLineBuffer, 8, 2) = '01' then              

with

lineTypeBuffer :=   Copy(fileLineBuffer, 8, 2);
if  lineTypeBuffer = '01' then                   

or

if  (fileLineBuffer[8] = '0') and (fileLineBuffer[9] = '1') then 

but it did not help. Any suggestions on how I should approach this problem?

P.S. Tried running it on Win7 32 bit and Win7 64 bit - no difference P.P.S. sorry for the long question.

Upvotes: 2

Views: 1721

Answers (1)

David Heffernan
David Heffernan

Reputation: 613572

The only explanation for

Copy(fileLineBuffer, 8, 2) = '01'

resulting in an access violation is that you have corrupted the heap.

Something else in your program is writing out of bounds and corrupting the heap. Such problems can be tricky to diagnose because the fault is typically in one part of the code, but the error occurs elsewhere. Some code corrupts the heap, and then a subsequent heap operation fails because of the earlier heap corruption.

I am confident in my diagnosis because Delphi string variables are known to work, Copy is known to work, and string equality testing is known to work. In other words there is no fault in the line of code at which the error occurs. Ergo the error is elsewhere.

Some debugging tools that might help:

  • FastMM in full debug mode.
  • Range checking (enabled from the project's compiler options).

Upvotes: 2

Related Questions