Pointers - Is it safe to point to invalid memory?
Paul Backus
snarwin at gmail.com
Sat Aug 16 21:58:30 UTC 2025
On Saturday, 16 August 2025 at 11:56:43 UTC, Brother Bill wrote:
> It is obvious that reading or writing to invalid memory can
> result in "undefined behavior".
> But is merely pointing to invalid memory "harmful"?
>
> The documentation states that going one past the last element
> of a slice is acceptable.
> But is it also safe to go 10, 100 or 1000 items past the last
> element of a slice?
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.
The way D prevents undefined behavior in `@safe` code is by
preventing the *creation* of unsafe values. For example, you
cannot perform pointer arithmetic, or convert an integer to a
pointer, because the pointers resulting from these operations may
point out of bounds. However, once an unsafe value has been
created, there is no safeguard to prevent it from being *used* in
`@safe` code.
This means that if you want to avoid undefined behavior, you must
be very careful not to create unsafe values in `@system` code and
pass them as inputs to `@safe` code--either directly as function
arguments, or indirectly via struct/class/module variables.
[1]: https://dlang.org/spec/function.html#safe-values
More information about the Digitalmars-d-learn
mailing list