Why is &array[0] @safer than array.ptr?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 25 14:59:55 PST 2017


On Wednesday, January 25, 2017 22:46:10 David Nadlinger via Digitalmars-d-
learn wrote:
> On Tuesday, 24 January 2017 at 11:38:16 UTC, Jonathan M Davis
>
> wrote:
> > It seems _slightly_ better from a safety perspective but only
> > slightly.
>
> Wrong – one is correct, the other is not. This is because every
> pointer in SafeD is dereferencable. Pointer arithmetic is not
> allowed in SafeD, so your concerns about reading from other
> memory do not apply.

Yes, but my point is that you're normally only going to use .ptr to pass
something to a C function, and even if you're doing more with it in D, odds
are, you're going to be doing pointer arithmetic. All &arr[0] does over
arr.ptr is check the first element. It makes it @safe, but then everything
else you're going to be doing after that almost certainly won't be @safe.
And when you combine it with marking C function @trusted, this is actually
pretty bad. It makes it trivial to do something like

extern(C) int cFunc(int* ptr, size_t length) @trusted;

auto result = cFunc(&arr[0], 12);

and have it be considered @safe, when it's not @safe at all. Now, most code
would then do

auto result = cFunc(&arr[0], arr.length);

so in practice, it won't usally be a problem, but it makes it easy to have
code treated like it's completely @safe when in fact it isn't. Now, really,
the fix there is to not mark the C function as @trusted and require that the
caller make sure they pass in arguments that are @safe, but at least if they
were doing

auto result = cFunc(arr.ptr, arr.length);

the compiler would have caught that it was @system even with the C function
being marked as @trusted, whereas if you do &arr[0], it wouldn't.

So, yes, if all you're planning to do is look at the pointer to the first
element in the array, then &arr[0] is safer, but odds are quite low that
that's actually what you're going to do, and in all of the other cases, you
might as well just use .ptr. So, telling folks to go use &arr[0] instead of
.ptr doesn't seem very helpful to me.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list