[Issue 22331] New: spec is incorrect regarding interfacing C with GC and local variables

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Sep 22 19:44:01 UTC 2021


          Issue ID: 22331
           Summary: spec is incorrect regarding interfacing C with GC and
                    local variables
           Product: D
           Version: D2
          Hardware: All
               URL: https://dlang.org/spec/interfaceToC.html#storage_alloc
                OS: All
            Status: NEW
          Keywords: spec
          Severity: normal
          Priority: P1
         Component: dlang.org
          Assignee: nobody at puremagic.com
          Reporter: schveiguy at gmail.com

For reference:


When a local variable is kept in a temporary register, the GC will not see it
after that register is used for something else. This means the object can be

This becomes a problem when you store the pointer outside the GC's view. The
spec currently lists the following as a remedy for such a thing:

> Leaving a pointer to it on the stack (as a parameter or automatic variable), as the garbage collector will scan the stack.

Typically, one leaves it on the stack by declaring an automatic variable, and
assigning it to that pointer. However, if the compiler notices that the
variable isn't used later on, it will not actually put even local variables on
the stack. This results in the object sometimes being collected seemingly when
the local variable is still in scope and should be referencing the block.

The spec should be changed to remove this possible remedy, or the remedy should
be clarified to outline how exactly to ensure that a variable gets put on the

Advanced optimizers are working against this goal by trying to avoid writing
registers to memory if it can avoid doing so. This may require changes to the
compiler and/or library to provide a good way to ensure the stack is storing
the data. If none of that is possible, the remedy should be removed.

Other languages that rely on a GC have a mechanism that does this exact

C#: `GC.KeepAlive`:
Go: `runtime.KeepAlive`: https://pkg.go.dev/runtime#KeepAlive

In both those examples, the function itself does nothing, it is just an
intrinsic to the compiler to note that the lifetime of the object should last
until at least that line.


More information about the Digitalmars-d-bugs mailing list