@trusted assumptions about @safe code

Steven Schveighoffer schveiguy at gmail.com
Tue May 26 15:41:12 UTC 2020


On 5/25/20 8:22 PM, ag0aep6g wrote:
> On 26.05.20 01:47, Dukc wrote:
>> No, `f` should be just dead `@system`. If you call f with a string 
>> which does not point to null, but is empty, boom!
> 
> Right. I can fix that by changing
> 
>      immutable(char)* c = s.ptr;
> 
> to
> 
>      immutable(char)* c = &s[0];
> 
> correct?

Yes, I was going to point that out too. But it doesn't affect the main 
point.

The main problem is that f does not provide a safe value to g. @safe 
code can always mess up if handed garbage. One might say that f should 
not be @trusted. But that just means NO functions could be trusted. If 
you cannot trust the semantic expectations of the functions you are 
calling to hold true, then you cannot write @trusted code ever. I mean, 
someone could do this inside memcpy:

size_t memcpy(void *dst, void *src, size_t length)
{
    *(size_t *)(dst + length + 10) = 0xdeadbeef;
    ...// normal implementation
}

And violate safety that way. So does that mean you can never use memcpy 
inside @trusted functions *just in case* it did something like this?

I get what you are saying, that it would be nice if one can just write 
@safe code and never worry that you might violate any memory rules. But 
in reality, you still have to implement the function as designed, and 
unless you do that, you are not going to be memory safe, period. The 
only call stacks that would be "safe" were ones that were @safe all the 
way down. And then @safe becomes essentially useless.

-Steve


More information about the Digitalmars-d mailing list