Release D 2.079.0

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Mar 6 07:11:24 UTC 2018


On Tuesday, March 06, 2018 05:34:39 psychoticRabbit via Digitalmars-d-
announce wrote:
> On Tuesday, 6 March 2018 at 05:22:58 UTC, Void-995 wrote:
> > Can somebody explain how &array[0] is more safe than array.ptr?
> > Just want to understand why second statement isn't allowed in
> > safe anymore.
>
> int[] a;
> writeln(&arr[0]); // good - runtime produces a
> core.exception.RangeError
> //writeln(arr.ptr); // what do you think will happen here?

That example actually should be perfectly @safe, because the array is null,
and it's using writeln. Dereferencing null is @safe, because it segfaults
and thus can't corrupt memory or access invalid memory. You obviously don't
want it to happen, but it's @safe. Also, passing a pointer to writeln is
fine, because it's just going to print the value, so that's @safe too, even
if the pointer value is garbage.

The problem is when the dynamic array's ptr points to something other than
null, and its length is 0. a[0] does bounds checking, so &a[0] is only valid
if the dynamic array's length is greater than 0, whereas a.ptr would happily
give you a value even if the array's length is 0, and in that case, it's not
valid to dereference that pointer. And depending on what that pointer points
to, it could corrupt memory or access invalid memory if you dereference it.

So, in _most_ cases, using ptr is actually fine, but because it's not
_always_ @safe, the compiler has to treat it as @system. It was previously
thought to be fine, because the case where a dynamic array is empty but
non-null had not been considered when deciding whether ptr could be used in
@safe code.

- Jonathan m Davis



More information about the Digitalmars-d-announce mailing list