While testing a few ideas with pointers, I bumped into a behavior not very clear to me.
During the development of one of the modules I'll be using in a project of mine, there came a point where I decided I'll simply assign the address of a pointer variable passed as a paramater as the value of one of an object's fields.
While writing the code for the said object's destructor, I decided to test what would happen to the variable, whose address I've assigned to an object's field, after I've applied Dispose() to the latter.
Here's a sample of what I was trying to do:
program BankTest;
var BankCredit : PCredit; BankSample : PBank;
begin New(BankCredit); BankCredit^ := 1000;
New(BankSample, BankCredit); BankSample^.Destroy; writeln(BankSample^); Dispose(BankCredit); end.
TBank.Create has this:
constructor TBank.Create(amount : PCredit); begin New(Self.AccountBalance); Self.AccountBalance := amount; end;
TBank.Destroy has this:
destructor TBank.Destroy; begin Dispose(Self.AccountBalance); end;
I get no errors or warnings (compiled with -O2 and -Wall), but when I try to run the resulting example, I get a `Segmentation fault' where writeln(BankSample^) is.
Here are my questions:
1) Is this correct behavior according to the standards? I know that doing two New()'s on the same pointer is a recipe for disaster, but it is unclear to me whether the same applies to this scenario.
2) If this is correct (i.e., I'm doing something I shouldn't be doing), then why doesn't GPC catch it? If this is already planned, then I guess I should just be more careful; but if it isn't, would it be hard to implement this?
I apologize for the long message, but all of the Pascal resources I have aren't very clear about this particular situation. Any clues as to where I should look (and/or help in general) would be greatly appreciated.
TIA.