Pointers - Is it safe to point to invalid memory?

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Sat Aug 16 22:31:33 UTC 2025


On 17/08/2025 10:28 AM, 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?
> 
> Andy

All pointer arithmetic is not valid in @safe code.

Arbitrary pointers values become @system, and are not accessible in 
@safe code. Thanks to @system variables DIP.

It has been addressed.

This isn't just an us thing, other native languages are now going in the 
direction of disallowing arbitrary pointers. They may only point to 
valid memory.

If the spec says otherwise, that needs fixing.



More information about the Digitalmars-d-learn mailing list