[fpc-devel] Capturing addresses

Jonas Maebe jonas at freepascal.org
Sun Nov 10 14:36:00 CET 2019


Hi,

Does anyone know what the accepted/excepted behaviour is regarding the
capture of addresses of var/out/const-by-address/constref parameters?

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.

I would like to teach the compiler to be able to assume that addresses
of variables are not captured merely because they are passed by
reference. There will also be a switch to toggle this assumption,
because fortunately it the behaviour is completely defined by the callee
side (so if you know that a unit does this, compiling that unit
appropriately is sufficient to ensure it will always work correctly).

The question is: should the compiler by default assume that such
addresses are not captured, or that they are captured? Does anyone know
if a lot of code exists that does this?


Jonas


More information about the fpc-devel mailing list