Hacker News new | ask | show | jobs
by TinkersW 204 days ago
That is actually memory safe, as null will always trigger access violation..

Anyway safety checked modes are sufficient for many programs, this article claims otherwise but then contradicts itself by showing that they caught most issues using .. safety checked modes.

3 comments

It is undefined behavior. You cannot make a claim about what it will always do.
As a fun example, I worked on a safety-critical system where accessing all-bits-zero pointers would trigger an IRQ that jumped back to PC + 4, leaving the register/variable uninitialized. Great fun was had any time there was LR corruption and CPU started executing whatever happened to be next in memory after function return.
Hahahaha well that behaviour is certainly fun!

I recently had a less wild but similarly baffling experience on an embedded-but-not-small device. Address 0 was actually a valid address. We were getting a HardFault because a device driver was dereferencing a pointer to an invalid but not-null address. Working backwards, I found that it was getting that invalid address not from 0x0 but rather from 0xC… because the pointer was stored in the third field of a struct and our pointer to that struct was null.

   foo->bar->baz->zap
Foo = 0, &bar = 0xC, baz = invalid address, *baz to get zap is what blew up.
>null will always trigger access violation..

No, it won't. https://gcc.godbolt.org/z/Mz8sqKvad

Oh my bad, I read that as nullptr, I use a custom optional that does not support such a silly mode as "disengaged"
How is that an optional then?

The problem is not nullopt, but that the client code can simply dereference the optional instead of being forced to pattern-match. And the next problem, like the other guy mentioned above, is that you cannot make any claims about what will happen when you do so because the standard just says "UB". Other languages like Haskell also have things like fromJust, but at least the behaviour is well-defined when the value is Nothing.

What do you return if there is no value set? That’s the entire point of optional.
You didn't read this, did you? https://alexgaynor.net/2019/apr/21/modern-c++-wont-save-us/

It's not a pointer.