memory safety checks and trust
Walter Bright
newshound2 at digitalmars.com
Sat Apr 11 02:57:03 UTC 2020
On 4/10/2020 6:21 PM, Adam D. Ruppe wrote:
> ```
> void main() {
> int a;
> b ~= &a;
> }
>
> int*[] b;
> ```
>
> trust.d(3): Error: copying & a into allocated memory escapes a reference to
> local variable a
>
>
> (Interestingly, `b = [&a]` instead of ~= passes muster. What's the difference?
> Just another bug in this?)
You will get the error with -preview=dip1000. Since that will eventually be the
default, it's not a bug.
You can get it to pass without error with the following:
@system int* foo(int* p) { return p; }
@system void test() {
int a;
b ~= &a;
b ~= [foo(&a)];
}
int*[] b;
The compiler will inline foo(). I highly recommend annotating such code with
&system.
> But the inconsistency isn't why I'm posting right now, it is my fear that D is
> losing faith in me. There seems to be no way to say "trust me" to the compiler.
> Note that I'm not even using any switches to dmd, and adding @trusted had no
> effect.
>
> One of the nice things about D is that I very rarely feel like I am fighting the
> language (unless I'm working under constraints like -w and @safe pure nothrow
> @nogc stuff, but that's why I just don't use those!). From low-level bit
> twiddling to high level "just make it work", the D language usually works with
> me, a few exceptions excluded - but when those happen, you can cast or whatever
> to tell it to trust me.
If @system isn't letting you do what you need to do, let me know.
More information about the Digitalmars-d
mailing list