Pointers - Is it safe to point to invalid memory?
Paul Backus
snarwin at gmail.com
Sun Aug 17 15:05:32 UTC 2025
On Saturday, 16 August 2025 at 22:28:15 UTC, Andy Valencia wrote:
> On Saturday, 16 August 2025 at 21:58:30 UTC, Paul Backus wrote:
>> Creating a pointer that points out-of-bounds does not, by
>> itself, result in undefined behavior.
>>
>> However, such a pointer would not be considered a [safe
>> value][1], because dereferencing it *would* result in
>> undefined behavior.
>
> I'm just pondering whether the intention was to accomodate this
> looping pattern:
>
> ```d
> int sum_values(int* p, uint nval) {
> int result = 0;
> foreach(_; 0 .. nval) {
> result += *p++;
> }
> return result;
> }
> ```
>
> A C idiom (I've so very much embraced not using pointers in my
> D world) which technically leaves "p" pointing beyond the
> memory range. Perhaps this is the special case being addressed?
I am not sure what "special case" you are referring to, so I will
try to explain from first principles.
In C, it is UB to *create* an out-of-bounds pointer, *except* for
a pointer that is one element past the end of an array, which is
allowed. (Source: [C11 § 6.5.6 ¶ 8][1]) The intent of this
exception is to allow idioms like the one above.
In D, merely *creating* an out-of-bounds pointer is never UB. In
general, D tries to avoid making things UB unless it is
absolutely necessary to do so, and that is probably why D is less
strict than C here.
In both C and D, it is always UB to *dereference* an
out-of-bounds pointer.
[1]: https://port70.net/~nsz/c/c11/n1570.html#6.5.6p8
More information about the Digitalmars-d-learn
mailing list