@trusted assumptions about @safe code
ag0aep6g
anonymous at example.com
Tue May 26 13:16:44 UTC 2020
On 26.05.20 11:13, Petar Kirov [ZombineDev] wrote:
> On Monday, 25 May 2020 at 23:04:49 UTC, ag0aep6g wrote:
[...]
>> char f(string s) @trusted
>> {
>> immutable(char)* c = s.ptr;
>> writeln(g(* cast(size_t*) &c));
>> return *c;
>> }
[...]
> 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`).
I think you're misreading the code. It's not reading size_t.sizeof bytes
starting at c. It's reinterpreting the pointer c itself as a size_t.
> 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.
Great. So far the majority opinion seems to be that f is invalid from
the start, and calling g like that just can't considered be safe. I like it.
More information about the Digitalmars-d
mailing list