[fpc-pascal] dynamic array and new/dispose

Jonas Maebe jonas.maebe at elis.ugent.be
Thu Feb 3 20:18:26 CET 2011


On 02 Feb 2011, at 17:26, Amit Bueno wrote:

> Seems that I found a workaround.
> When calling the NewSubChunk in the following syntax:
> SubChunks[NewSubChunk]^.read(fl);  /// raise an exception.
>  
> While
> MyIndex := NewSubChunk;
> SubChunks[MyIndex]^.read(fl);  /// raise an exception.
>  
> Doesn't raise any excetion….
> Maybe the experts could say why, I don't know why…

The reason is that SubChunks (a dynamic array) can be nil before NewSubChunk() (a function that allocates 2 extra elements for that array) is called. So if the compiler first loads SubChuncks (=nil) in a register, then calls NewSubChunk, and then indexes this nil pointer using that function result, you will get at an access violation.

The original code is wrong because Pascal does not define a particular order in which such expressions have to be evaluated by the compiler. In general, calling functions with side effects inside expressions that can be affected by those side effects is very bad practice (and dangerous, as you've noticed).

The fact that it doesn't crash in the Delphi version that you tested is pure coincidence, and it may very well crash is older or newer versions.


Jonas


More information about the fpc-pascal mailing list