dispose: bug or feature?

Adriaan van Os gpc at microbizz.nl
Mon Dec 10 09:16:59 CET 2007


Russell Whitaker wrote:

> Given a pointer p, dispose(p) does not set p to nil.
> 
> This program,
> 
> program tst;
> type
>   ptr = ^string;
> var
>   p : ptr;
> begin
>   p := new( ptr, 20 );
>   p^ := "abc";
>   writeln( p^ );
>   dispose( p );
>   p := nil;
>   if p = nil then
>     writeln("OK");
>   dispose( p );
>   writeln( p^ );
> end.
> 
> as is gives you
> 
> abc
> OK
> segmentation fault
> 
> The seg fault is from the last writeln.
> If you comment out the line "p := nil", the second "dispose" causes
> a core dump.
> If you comment out both "p := nil" and the second "dispose" you get
> 
> abc
> abc
> 
> and that's also an error.

For this very reason, I always use allocation/deallocation wrappers that do something like

procedure mydispose( var p: pointer);
begin
   if p <> nil
     then begin
       dispose(p);
       p:=nil
     end
end;

> I do not know what side effects you might get if you caused "dispose"
> to set the pointer to nil.

Neither do I know whether the standard allows it. But it's quite a useful feature.

Regards,

Adriaan van Os






More information about the Gpc mailing list