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
              • ... 0xEAB via Digitalmars-d-learn
              • ... Brother Bill via Digitalmars-d-learn
              • ... Monkyyy via Digitalmars-d-learn
              • ... Brother Bill via Digitalmars-d-learn
              • ... Monkyyy via Digitalmars-d-learn
              • ... Monkyyy via Digitalmars-d-learn
              • ... Ali Çehreli via Digitalmars-d-learn
              • ... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
              • ... Monkyyy via Digitalmars-d-learn
  • Re: Pointers - I... Monkyyy via Digitalmars-d-learn
  • Re: Pointers - I... Paul Backus via Digitalmars-d-learn
    • Re: Pointer... Andy Valencia via Digitalmars-d-learn
      • Re: Poi... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
      • Re: Poi... monkyyy via Digitalmars-d-learn
      • Re: Poi... H. S. Teoh via Digitalmars-d-learn
      • Re: Poi... Paul Backus via Digitalmars-d-learn
        • Re:... monkyyy via Digitalmars-d-learn
        • Re:... Ali Çehreli via Digitalmars-d-learn

Reply via email to