dip1000 and preview in combine to cause extra safety errors

Steven Schveighoffer schveiguy at gmail.com
Thu Jun 9 15:30:47 UTC 2022


On 6/9/22 10:46 AM, Dennis wrote:
> On Thursday, 9 June 2022 at 01:18:30 UTC, Steven Schveighoffer wrote:
>> For some reason, while you can't return a pointer to a local, you can 
>> return a scope pointer.
> 
> A pointer to a local is guaranteed to be a dangling pointer when you 
> return it, while a `scope` pointer is not guaranteed to be memory with 
> limited lifetime when you return it. `scope` is only a conservative 
> compile-time approximation of what's actually happening, which makes it 
> susceptible to false positives:
> 
> ```D
> int* f(int x) @safe {
>      int* p = &x; // p is inferred scope here
>      p = new int; // p is no longer pointing to stack memory
>      return p;    // Error: scope variable `p` may not be returned
> }
> ```
> This function could be permitted as @system or @trusted code.

I want to stress that I'm actually OK with the current situation as far 
as returning scope pointers as not-scope pointers in @system code. I've 
returned &this quite a bit in my code.

What is not OK is the compiler turning actual requests for GC allocation 
into stack allocations based on that. At this point, it's a literal, but 
if it did this for e.g. `new T`, we are in for a lot of trouble.

I'll ask, is it undefined behavior to return a scope pointer as a 
non-scope pointer? If so, should we make UB so easy to do?

This obscure interaction between the attributes, and the weird 
relationship between the scopeness of the return value (you can't label 
the return value as scope, you have to instead label the parameter as 
return), paired with the odd choices the compiler makes, are going to 
lead to insanely hard-to-find memory corruption problems.

In any case, I filed a bugzilla issue: 
https://issues.dlang.org/show_bug.cgi?id=23175

-Steve


More information about the Digitalmars-d mailing list