www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 24213] New: [DIP1000] Scope pointer can escape via non-scope

https://issues.dlang.org/show_bug.cgi?id=24213

          Issue ID: 24213
           Summary: [DIP1000] Scope pointer can escape via non-scope
                    parameter of delegate
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: normal
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: snarwin+bugzilla gmail.com

As of DMD 2.105.2, the following invalid program compiles and runs without
errors:

---
alias Dg = void delegate(int* p)  safe pure nothrow;

void main()  safe
{
    int* escaped;

    int n;
    Dg dg = delegate void (int* p) { escaped = p; };
    dg(&n);
}
---

This program is invalid because, in  safe code, it assigns the address of the
variable `n` to the variable `escaped`, which has a longer lifetime than `n`.

The expression `dg(&n)` should cause a compile-time error, because it assigns
the scope pointer value `&n` to the non-scope parameter `p`.

The compiler allows this because, due to the rules laid out in "Inferred scope
parameters in pure functions" [1], it believes that the parameter of `dg`
cannot escape. However, these rules do not account for the possibility that a
pure delegate may escape a non-scope parameter via its nested context.

[1]: https://dlang.org/spec/function.html#pure-scope-inference

--
Oct 30 2023