0

I have read most of the posts here on invalid pointer operations in Delphi and they don't seem to apply to this case... Trial and error led me to the line with the problem but it doesn't make any sense to me. In this example, a dynamic array of records is populated with the contents of a text file as it parses it. Everything works perfectly except when the memory allocated to the dynamic array is released - in that case I receive an "Invalid Pointer Operation". When I change the line in question from an ifthen statement to a classic if-then, it works.

My question is simple: Why does the first one cause it to fail to release the memory but the but the second one succeeds?

First Example:

TempFTDB[ci].FTText := ifthen(TempHolder = '', '', TempHolder + #13#10) + lr;

Second Example:

if tempholder = '' then
    TempFTDB[ci].FTText := lr
else
    TempFTDB[ci].FTText := tempholder + #13#10 + lr;

The line that releases the memory is:

TempFTDB := nil;

Further clarification: TempFTDB is a local variable and there are no other lines that free it's memory. It is on the "TempFTDB := nil" line that the error occurs.

RRUZ
  • 134,889
  • 20
  • 356
  • 483
b-p
  • 307
  • 3
  • 10

2 Answers2

0

Usually this kind of problem when using IfThen is because the IfThen method expects 2 strings, as you can see in the method signature:

function IfThen(AValue: Boolean; const ATrue: string; AFalse: string = ''): string;

I don't know if the code you posted is the actual code, but I can guess that the "False" value is in a wrong state and the IfThen method will execute both conditions, always.

So if you are passing a method in the "False" value, and this method depends on your condition being false for it to be executed, this can lead to unexpected behavior, because it will always be executed.

Fabio Gomes
  • 5,914
  • 11
  • 61
  • 77
0

Okay... It turns out that the above was a red herring, sort of. The error came back whenever the above mentioned routine (excerpted above) was run a second time - certainly sounds like unallocated memory... Just prior to the code sited above was a routine for renumbering items in a temporary array of records and therein was the problem... (an embarrassing little mistake..)

I had:

for i := 0 to length(FTDBFileBuffer_RTF) do
  begin
    FTDBFileBuffer_RTF[i].RecordNo := NewRecordNumber;
  end;

instead of

for i := 0 to length(FTDBFileBuffer_RTF) - 1 do //notice the - 1
  begin
    FTDBFileBuffer_RTF[i].RecordNo := NewRecordNumber;
  end;

Now the issue is just academic... Why would the presence or absence of the ifthen command force the error to show?

b-p
  • 307
  • 3
  • 10
  • Errors will become erratic when memory is falsely overwritten, like in your case when writing a record into a non-allocated memory area. – LU RD May 08 '12 at 08:30