EAccessViolation apparently being thrown by FreeMem
In the following method, FreeMem(), throws an EAccessViolation. What are the possible reasons?
procedure TCustomDataset.FreeRecordBuffer(var Buffer: PChar);
begin
FreeMem(Buffer);
end;
EDIT: As far as I understand TDataset Buffers are only allocated in:
function TCustomDataset.AllocRecordBuffer: PChar;
begin
Result := AllocMem(GetBufferSize);
end;
and only freed in FreeRecordBuffer()
Now I've checked and in my case 2 buffers are allocated, the first one gets freed without a hitch, but the second causes FreeMem()开发者_运维技巧 to throw a EAccessViolation. I've also check(by writing down the pointer addresses) that both the address were given by AllocRecordBuffer() are passed to FreeRecordBuffer() and nothing else.
According to Delphi Basics FreeMem() should only throw an EInvalidPointer when the pointer is invalid.
EDIT: Found the problem, I overwrote memory.
I assume you mean EAccessViolation. Probably Buffer is already freed or otherwise invalid. It's hard to say more without at least a tiny bit of context.
Basically what happened was I wrote over the end of the memory buffer I allocated and this somehow caused Free() to EAccessError.
This could be because both buffers were adjacent in memory(strangly they were 4 bytes appart) and by writing over the end I overwrote some information stored by delphi before each buffer in the second buffer, thereby possibly making the buffer think it's longer than it actually is and causing it to try and free memory that doesn't belong to the program.
精彩评论