[fpc-devel] Capturing addresses
Martin Frb
lazarus at mfriebe.de
Sun Nov 10 14:58:22 CET 2019
On 10/11/2019 14:36, Jonas Maebe wrote:
> For example:
>
> var
> g: longint;
> p: plongint;
>
> procedure test(var l: longint);
> begin
> p:=@l;
> end;
>
> begin
> test(g);
> end.
>
> After test() executes, p now contains the address of g (the '@' operator
> does not return the address of g's address on the stack; it returns the
> actual address of g). This means that g's address has been captured by
> test(). This can obviously lead to wrong/dangerous situations, e.g. if g
> was not a global variable, but a local variable of another procedure.
> That said, it is a legal expression.
>
Your example shows the safe case (p is and will continue to be safe).
In the unsafe case (g to be a local var), this is similar to none "var
param"
var
p: plongint;
procedure test(l: longint);
begin
p:=@l;
end;
p will be a dangling pointer, after "test" exited.
The same as in your example, but with the case that "g" is local, p
becomes dangling when "g" goes out of scope.
So I am trying to understand what the difference (in terms of safety)
is? (except that the none "var param" is always unsafe, the "var param"
is only sometimes unsafe)?
Also out of interest, what would change if you ...
> teach the compiler to be able to assume that addresses
> of variables are not captured merely because they are passed by
> reference
More information about the fpc-devel
mailing list