我有一个 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/