windows - Delphi 中字符串操作的访问冲突

标签 windows delphi delphi-7 access-violation

我有一个 Delphi 应用程序,它从文件中读取数据并将其存储在数组中。文件中的每一行包含一个地址、lineTypeIndicator 和数据。这是算法(包含我认为至关重要的代码):

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;

每次用户单击表单上的相应按钮时都会执行此代码。它在执行的前几次运行,但在几次运行后我得到了这个:

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

对我来说,这听起来像是某种堆溢出。我尝试过更换

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

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

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

但这并没有帮助。 关于如何解决这个问题有什么建议吗?

附注尝试在 Win7 32 位和 Win7 64 位上运行 - 没有区别 附言抱歉问了这么长的问题。

最佳答案

唯一的解释

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

导致访问冲突的原因是您损坏了堆。

程序中的其他内容正在写入越界并损坏堆。此类问题很难诊断,因为故障通常出现在代码的某一部分,但错误却发生在其他地方。某些代码损坏了堆,然后后续的堆操作由于之前的堆损坏而失败。

我对我的诊断很有信心,因为已知 Delphi 字符串变量可以工作,Copy 可以工作,并且字符串相等性测试也可以工作。换句话说,发生错误的代码行没有错误。因此错误在其他地方。

一些可能有帮助的调试工具:

  • FastMM 处于完全 Debug模式。
  • 范围检查(通过项目的编译器选项启用)。

关于windows - Delphi 中字符串操作的访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18915383/

相关文章:

在同一个 system() 调用中连接两个命令

windows - 如何使用命令输出作为另一个命令的参数?

c++ - windows类型到linux

delphi - 如何在 Delphi 7 中的资源文件中使用 Skin 文件 (.asz) 文件

delphi - 项目 abc.exe 在 dxBar.pas 文件中引发了异常类 EListError,消息为 'List index out of bounds (0)'

python - Windows 命令提示符下的 Python 3.6 中找不到模块错误

delphi - 带分离器的面板布局

delphi - 如何为 Delphi 项目生成反向调用树?

delphi - 如何获取TSpeedButton的双击事件?

delphi - Delphi XE4 RAD Studio 中的 DFM 布局问题