memory safety checks and trust

Steven Schveighoffer schveiguy at gmail.com
Tue Apr 14 20:40:11 UTC 2020


On 4/14/20 4:14 PM, Walter Bright wrote:
> On 4/14/2020 10:16 AM, Steven Schveighoffer wrote:
>> That being said, I agree with the simple case of returning a pointer 
>> from a stack variable directly from a function being disallowed. That 
>> also can be easily worked around, which should probably be required, 
>> but is never correct anyway.
> 
> Oh, it can be correct, when one wants to examine the stack pointer 
> value. I've used it for that purpose myself. (Examining the stack 
> pointer is valuable when determining whether other pointers are pointing 
> into the stack or not.)

Do you need to call a function to do that? Won't just &somevariable work?

Also, this compiles just fine, and gives you the stack pointer value:

size_t stackPtr() @system
{
   int i;
   return cast(size_t)&i;
}

> 
> As I replied to Timon, you're drawing a subjective (not objective) line 
> at what is acceptable or not.
> 

Yes, it's subjective. But so is common sense.

The objective line is that all should be allowed. I'm fine with that too 
if that means you can write useful memory safe @system code. It's an 
entirely valid and *consistent* proposal to say "@system just allows 
anything, including obvious memory errors. Use @safe if you want 
compiler restrictions."

Or, we could say, for the 0.00000001% of the time you want to get a 
stack pointer value, use a cast, which means the other 99.9999999% of 
the cases which are actually memory problems are helpfully caught. You 
must be able to see that there is a difference in common utility between 
needing to capture the stack pointer value, and wanting to utilize heap 
space.

It doesn't even make sense that array appending is somehow "the one 
thing" that causes problems, when you can pass stack pointers to 
functions which you don't control, slice static arrays, create stack 
pointers at will and *then* do whatever you want, etc. If there is a 
subjective story for this "feature" it has quite a few holes in it. It's 
like putting up a fence post instead of a fence to protect a space. It 
just ends up being more annoying than functional.

I can do this too, apparently since it's a TLS array and not a heap 
array, totes ok!

int*[1] arr;

void bar()
{
     int i;
     arr[0] = &i;
}

-Steve


More information about the Digitalmars-d mailing list