Comment #0 by snarwin+bugzilla — 2021-03-02T14:45:57Z
As of DMD 2.095.0, the following program compiles and exhibits undefined behavior at runtime:
---
struct S
{
int* p = cast(int*) 0xDEADBEEF;
}
@safe void main()
{
S s;
int n = *s.p;
}
---
To prevent this, the compiler must either forbid default initialization of types with unsafe `.init` values, or enforce that all default initializers are safe values. [1]
Related: issue 21664.
[1] https://dlang.org/spec/function.html#safe-values
Comment #1 by snarwin+bugzilla — 2023-11-10T21:07:39Z
This would also be fixed by having the compiler infer S.p as a @system variable based on its initializer.
Comment #2 by dlang-bot — 2024-03-30T15:48:57Z
@ntrel created dlang/dmd pull request #16347 "Require @system for field initializers with mutable reference types" fixing this issue:
- Require @system for field initializers with mutable reference types
Enabled with -preview=unsafeFieldInit.
Fixes Bugzilla 21675 - Unsafe aggregate field initializer causes undefined behavior in @safe code
https://github.com/dlang/dmd/pull/16347
Comment #3 by nick — 2024-03-30T18:02:22Z
Although the idea in the comment 2 would fix this, the current pull does not. Sorry for the noise.
Comment #4 by robert.schadek — 2024-12-13T19:14:58Z