memory safety checks and trust

Steven Schveighoffer schveiguy at gmail.com
Sat Apr 11 20:31:47 UTC 2020


On 4/11/20 6:01 AM, Johan wrote:
> On Saturday, 11 April 2020 at 02:57:03 UTC, Walter Bright wrote:
>> 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 OP's point was that exactly this does not compile. Trivial to test 
> online:
> https://d.godbolt.org/z/i8WFcs

It does if you write it correctly:

b ~= foo(&a);

That was Walter's point. Once you get out of one expression, the checks 
stop.

You can do this too:

auto p = &;
b ~= p;

Note that a more robust argument for the OP's point is that you can 
easily make sure the allocation isn't used outside the function. What if 
you need scratch space to deal with things?

e.g.:

@system void test() {
    int *[] buf;
    int a;
    buf ~= &a; // Same error
}

How is &a escaping here?

-Steve


More information about the Digitalmars-d mailing list