@trusted assumptions about @safe code
Petar
Petar
Tue May 26 09:13:32 UTC 2020
On Monday, 25 May 2020 at 23:04:49 UTC, ag0aep6g wrote:
> [..]
>
> 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"));
> }
>
> As the spec stands, I believe it allows f to be @trusted. The
> function doesn't exhibit undefined behavior, and it doesn't
> leak any unsafe values or unsafe aliasing. So it has a safe
> interface and can be @trusted.
>
As mentioned by others, it is incorrect to label `f` with
`@trusted` because:
1. It provides unsafe access to potentially out of bounds memory
- there's no guarantee that `s.length >= size_t.sizeof` is true
(in addition to the possibility of `s.ptr` being `null`).
2. It creates mutable aliasing to immutable memory and passes it
to another function. Casting away `immutable` could be safe iff
the mutable reference can't be used to modify the memory. So, `g`
must take a `const` reference to `size_t`, in order for `f` to
even begin to be considered a candidate for the `@trusted`
attribute.
More information about the Digitalmars-d
mailing list