What's the D equivalence?

Nick Treleaven nick at geany.org
Sat Mar 6 11:48:37 UTC 2021


On Friday, 5 March 2021 at 21:09:38 UTC, tsbockman wrote:
> Also, the guard region is of finite size and can be bypassed to 
> potentially silently corrupt memory when accessing the interior 
> of a sufficiently large type:
>
> void sowChaos(size_t length)(int[length]* ptr) @safe {
>     (*ptr)[length - 1] = 0xBAD; }
>
> If (int.sizeof * (length - 1)) happens to be the address of 
> memory writable by the current process, this will do bad things.

Yes, and due to `ref` it can occur even when it looks like a null 
dereference should have happened:

@safe:

void f(ref BigFixedArr b)
{
	// ... complex logic
	b[b.length-1] = 4; // possible memory corruption even on null 
trapping systems
}
void main()
{
	BigFixedArr* p;
	// ... complex logic
	f(*p); // at least if p is accidentally null, it will crash 
here, right? nope
}

This could be fixed by checking for null in @safe code when 
dereferencing a pointer passed to a `ref` parameter. But that 
doesn't fix the unsafety of the sowChaos example (although at 
least that isn't so confusing).


More information about the Digitalmars-d mailing list