@trusted assumptions about @safe code

Arine arine1283798123 at gmail.com
Tue May 26 00:57:52 UTC 2020


On Monday, 25 May 2020 at 23:04:49 UTC, ag0aep6g wrote:
> Deep in the discussion thread for DIP 1028 there is this little 
> remark by Zoadian [1]:
>
>> you can break previously verified @trusted code by just 
>> writing @safe code today.
>
> That statement fits something that occurred to me when trying 
> to lock down the definition of "safe interfaces" [2].
>
> Consider this little program that prints the address and first 
> character of a string in a convoluted way:
>
>     import std.stdio;
>     char f(string s) @trusted
>     {
>         immutable(char)* c = s.ptr;
>         writeln(g(* cast(size_t*) &c));
>         return *c;
>     }
>     size_t g(ref size_t s) @safe
>     {
>         return s;
>     }
>     void main() @safe
>     {
>         writeln(f("foo"));
>     }

You are passing a pointer into a function that takes a mutable 
size_t by reference and then use the pointer afterwards. You get 
what's coming to you if you think that's suitable for @trusted.

This is a good example that care must still be taken in @trusted. 
You are doing something dangerous, expect to be burned by it.

      char f(string s) @trusted
      {
          {
              immutable(char)* c = s.ptrl
              writeln(g(* cast(size_t*) &c));
              // var c invalidated by above function, don't use 
after this line
          }
          return s[0];
      }


More information about the Digitalmars-d mailing list