Neil Santos wrote:
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.
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,
No, it isn't. Don't know where you got this from.
but it is unclear to me whether the same applies to this scenario.
No, this scenario *is* a problem. ;-)
According to a standard it's an error that a processor is permitted to leave undetected. It's in the same category as using undefined values etc.
2) If this is correct (i.e., I'm doing something I shouldn't be doing), then why doesn't GPC catch it?
Tracking such things is possible, but with *very* high effort. (Both in terms of compiler code and runtime inefficiency.) If we allow combination with other languages, it becomes even harder if not impossible.
Some people suggest heuristics, such as setting undefined variables to certain "unlikely" values and runtime-testing for these, but they can only catch some of the problems, and are not completely reliable.
You can try linking the "Electric fence" library to catch some kinds of memory management errors. The same caveat as in the previous paragraph apply, but at least it's no big effort to do.
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.
I suppose that's because in most compilers (including GPC, BP, ...) it's just undefined behaviour.
Frank