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

Walter Bright <[email protected]> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |[email protected]

--- Comment #7 from Walter Bright <[email protected]> ---
Let's rewrite:

  class MyClass
  {
    void doSomething();

    void myMethod() @nogc
    {
        acceptsCallback((){ doSomething(); });
    }
  }

to make visible what is happening.

  class MyClass
  {
    void doSomething(MyClass this);

    void myMethod(MyClass this) @nogc
    {
        auto outer = &this;
        void func(MyClass* outer)
        {
            doSomething(*outer);
        }
        acceptsCallback(&outer.func);
    }
  }

func is a member of myMethod, not a member of MyClass. func's "this" pointer is
a reference to the stack frame of myMethod, not a reference to MyClass.
acceptsCallback() is allowed to squirrel away the address of func(), and could
access it after myMethod() has exited. This will result in corrupted memory.

The solution is for acceptsCallback to annotate its parameter with `scope`,
which says it will not preserve its argument past the lifetime of
acceptsCallback.

--

Reply via email to