C++ Logo

std-proposals

Advanced search

Re: [std-proposals] try else syntax for validity check

From: Oliver Hunt <oliver_at_[hidden]>
Date: Tue, 18 Feb 2025 14:09:50 -0800
> On Feb 18, 2025, at 11:53 AM, Jennifier Burnett via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> Actually the capability of detecting nullptr dereferences (or any invalid memory access in general) is built into pretty much all hardware nowadays. Detecting ALL nullptr references and throwing an exception would be entirely free on most machines (and in fact this is what the android java runtime does, unless they've changed it).

Producing specified behavior for a null dereference is not simply a matter of specifying the behavior of `*ptr` when ptr == nullptr, it requires specifying the behavior of `nullptr+offset`

e.g.

   ptr[x] = 0

If `ptr` is null, but `x` is large enough then `ptr[x]` may be a valid address, so the only way an implementation can produce a specified outcome to the null dereference is by requiring a null check on `ptr` prior to the actual load.

I assume this latter case is why dereferencing null is UB - the trivial case of `*nullptr` is easily specifiable as EB, but once there’s a runtime offset you can’t practically define a result without requiring a null check on the base address.

—Oliver

Received on 2025-02-18 22:09:54