Bug 15685 – &slice[$] should be allowed

Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2016-02-15T11:27:59Z
Last change time
2020-06-05T10:35:59Z
Assigned to
No Owner
Creator
naptime

Comments

Comment #0 by naptimeentertainment — 2016-02-15T11:27:59Z
It should be possible to get the address of the upper boundary of a slice by taking the address of slice[$]. Here is the address I want (and I hereby release this untested code snippet into the public domain): pragma (inline, true) inout(Elem)* addrOfDollar(Elem) (auto ref inout(Elem)[] slice) @trusted { import core.stdc.stdint : uintptr_t; immutable uintptr_t pHead = cast(uintptr_t) slice.ptr, // &slice[0] nmemb = slice.length, esize = Elem.sizeof, pDoll = nmemb * esize + pHead; // &slice[$] return cast(typeof(return)) pDoll; } But there are two issues with that: 1. I want to use the syntax &slice[$] instead of calling a function. 2. It doesn't work during CTFE.
Comment #1 by pro.mathias.lang — 2020-06-05T10:35:59Z
In order to get this address, you should do `slice.ptr + slice.length`. `&slice[$]` would give you an element *after* the array, so it's potentially pointing to unallocated / invalid / protected memory. It's a pointer you should *never* access. When writing C-style code, it's common to do `while (p++ < pend)` where `pend` is this pointer, but the type system can't guarantee you'll use it correctly. Also, that would break `@safe` code. So marking as `INVALID` since we don't want to allow it, and there's an easy workaround: use `ptr + length`.