3 ms·
> Here, instead of handling the error condition, I create an lvalue that points nowhere in case of an error because it then corresponds to (({ (void)0; })), re
by nextaccountic 1y ago
> Here, instead of handling the error condition, I create an lvalue that points nowhere in case of an error because it then corresponds to (({ (void)0; })), relying on the null sanitizer to transform it into a run-time trap for safety.
Isn't this undefined behavior?
- lmm 1y agoIn standard C yes. But any decent C compiler will offer stronger guarantees than the minimum that the standard requires, and presumably the "null sanitizer" they're referring to is one of them.
- pjmlp 1y agoAs usual, the problem is not what they have been offering for the last decades in tooling, rather what developers actually make use of. Unfortunely many keep needing education on such matters.
- playforclaude 1y agoAny decent C compiler will use loopholes in the standard to optimise your code :)
- shakna 1y agoMaybe, but it is defined for GCC: > You can store a null pointer in any lvalue whose data type is a pointer type. [0] Though, I would expect a complaint from clang, and clang-tidy. [0] https://www.gnu.org/software/c-intro-and-ref/manual/html_node/Null-Pointers.html https://www.gnu.org/software/c-intro-and-ref/manual/html_nod...
- uecker 1y agoIt is only undefined behavior if it is dereferenced, in which case the null sanitizer can be used to define it to trap, so safely terminate the program. But the example then also shows how you can make sure that this case is not even possible in the final program.
- nextaccountic 1y agoIt is actually dereferencing a null pointer (there is a * on the beginning of the definition of maybe_value). It is okay if you test for p.ok first, and UB otherwise. So it's like Option::unwrap_unchecked from Rust, not Option::unwrap that merely panics. Relying on sanitizers to catch UB can only work in a best effort basis, because the compiler can perform optimizations that rely on the fact that the program doesn't have UB (and produces broken code if there is UB - beyond what a sanitizer could catch) It would be much better to also provide another macro to abort the program if the maybe is nothing.
- layer8 1y agoThe null sanitizer is used to define the behavior, which is one of the ways a C implementation is allowed to handle situations whose behavior the C standard leaves undefined.