D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 15685 - &slice[$] should be allowed
Summary: &slice[$] should be allowed
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-02-15 11:27 UTC by naptime
Modified: 2020-06-05 10:35 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description naptime 2016-02-15 11:27:59 UTC
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 Mathias LANG 2020-06-05 10:35:59 UTC
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`.