News for hackers. Stuff that matters.
Re:A Guide to Undefined Behavior in C and C++ (2010) by jasonthorsness on Sunday March 16, 2025 @08:22PM (#43383937)
This is an area the newer languages get right - I don’t think Rust or Go has any undefined behavior? I wish they would have some kind of super strict mode for C or C++ where compilation fails unless you somehow fix things at the call sites to tell the compiler the behavior you want explicitly.
Re:A Guide to Undefined Behavior in C and C++ (2010) by zyedidia on Sunday March 16, 2025 @09:13PM (#43384226)
I think data races can cause undefined behavior in Go, which can cause memory safety to break down. See https://research.swtch.com/gorace for details.
Re:A Guide to Undefined Behavior in C and C++ (2010) by jjmarr on Sunday March 16, 2025 @08:55PM (#43384111)
> I wish they would have some kind of super strict mode for C or C++ where compilation fails unless you somehow fix things at the call sites to tell the compiler the behavior you want explicitly.

The C++ language committee _does not_ want to add more annotations to increase memory safety.

Re:A Guide to Undefined Behavior in C and C++ (2010) by anon-3988 on Sunday March 16, 2025 @09:31PM (#43384331)
Not even annotations. The committee standardize this https://en.cppreference.com/w/cpp/container/span/operator_at

So they clearly doesn't care so there's no point convincing them.

Re:A Guide to Undefined Behavior in C and C++ (2010) by maxlybbert on Monday March 17, 2025 @12:12AM (#43385149)
The committee tends to also provide bounds checked interfaces ( https://en.cppreference.com/w/cpp/container/span/at ). But that requires people to read the documentation, and based on the number of people who I see write "std::endl" when they really want "'\n'", I don't have much hope for that ("std::endl" both sends '\n' to the stream, and flushes it; people are often surprised about the stream getting flushed).
Re:A Guide to Undefined Behavior in C and C++ (2010) by AlotOfReading on Monday March 17, 2025 @12:23AM (#43385193)
We've known since the 80s that programmers almost always choose the more ergonomic interface and telling people they're holding it wrong doesn't scale.

Besides, throwing an exception is a terrible way to do range checking. There's a huge number of projects out there banning exceptions that would benefit from safe interfaces.

Re:A Guide to Undefined Behavior in C and C++ (2010) by shiomiru on Monday March 17, 2025 @03:14AM (#43385914)
> Besides, throwing an exception is a terrible way to do range checking. There's a huge number of projects out there banning exceptions that would benefit from safe interfaces.

I thought "banning exceptions" would mean fno-exceptions, turning the throw into an abort - that's pretty good for a systems programming language, no?

What other way would you propose?

Re:A Guide to Undefined Behavior in C and C++ (2010) by anon-3988 on Monday March 17, 2025 @05:21AM (#43386539)
Make it explicit that the API can fail. Panicking is not acceptable in systems programming. Force me to handle all the cases.
Re:A Guide to Undefined Behavior in C and C++ (2010) by imtringued on Monday March 17, 2025 @05:51AM (#43386698)
I'm not trying to be provocative, but I genuinely am not seeing what the benefit of this "doctrine" is if the end result is a bunch of if else statements that do nothing, but bubble the error up and then exit the process anyway.

Panicking is in no way different from say Undefined Behavior, with the exception that panicking tends to be "loud" and therefore fixed promptly.

Re:A Guide to Undefined Behavior in C and C++ (2010) by anon-3988 on Monday March 17, 2025 @08:17AM (#43387682)
EDIT: HN formatting is absolute horrendous so here's a pastebin https://pastebin.com/raw/BUJBAqc1

> but bubble the error up and then exit the process anyway.

What is so bad about this? Its only a problem because all languages are not ergonomic. Even Rust. Here's how to do it properly in my mind.

What I am proposing is not Rust, but what I wish Rust would have been.

First, you have functions that cannot fail

``` fn not_failable() -> Result<u32, ()> { return 0; } ```

Notice that the function still returns Result<T,E> but the error is (). Now what happens if the function can fail?

``` fn failable(value) -> Result<u32, () | A | B | C | D> { if value == 0 { return Ok(0); } else if value == 1 { return Err(A()); }else if value == 2 { return Err(B()); }else if value == 3 { return Err(C()); }else if value == 4 { return Err(D()); } } ```

Notice that we don't have to specify a type for the errors, they are just the unions of all the error types that is possibly returned by the function. This union could be inferred by the type system to be ergonomic (meaning it can be omitted from the type signature for ergonomic purposes)

You might think that this is almost like exceptions. And you are right, but this is where exceptions got wrong, the user of this function.

When using this function, you are forced to handle all the possible error types (exceptions) returned by the function

``` fn use1() -> Result<u32, () | C | D> { match failable() { Ok(v) => {} Err(A) => {} Err(B) => {} e => return Err(e), } } ```

Notice 2 things:

1. You are FORCED to handle all the possible exceptions. 2. You can specify which exceptions you want to handle and what you throw back. The difference to try/catch here is just the syntax. 3. The function signature can be automatically be duduced by the fact that A and B are already handlded, and that this function can only throw C or D now.

Now you might complain about ergonomic, why can't things just blow up the moment anything bad happens? I propose a trait that will be automatically be implemented for all Result<T,E>

``` impl Unwrap for Result { fn unwrap(self) -> u32 { match self() { Ok(ok) => return ok, Err(err) => panic!("error"), } } } ```

Which means that you can simply do this,

``` fn fail_immediately() -> Result<u32, ()> { return failable().unwrap(); } ```

Or, if you want to bubble up the errors, you can use ?

``` fn fail_immediately() -> Result<u32, A | B | C | D> { return failable()?; } ```

Re:A Guide to Undefined Behavior in C and C++ (2010) by eddd-ddde on Monday March 17, 2025 @08:46AM (#43387953)
That looks just like zig error handling to me. The only missing component being that errors themselves are just a tag without any more data content.
Re:A Guide to Undefined Behavior in C and C++ (2010) by AlotOfReading on Monday March 17, 2025 @11:39AM (#43389677)
There are systems banning exceptions that aren't allowed to crash. The software running cars and planes for example, or LLVM.
Re:A Guide to Undefined Behavior in C and C++ (2010) by nemetroid on Monday March 17, 2025 @04:33PM (#43392470)
Ending your string literal with \n is much easier than using std::endl.
Re:A Guide to Undefined Behavior in C and C++ (2010) by AlotOfReading on Monday March 17, 2025 @10:49PM (#43395286)
The comment was about bracket notation versus .at()

My only opinion on the \n versus std::endl discussion is that people set overly aggressive linting rules that always flag endl even when flush is intended.

Re:A Guide to Undefined Behavior in C and C++ (2010) by tialaramex on Sunday March 16, 2025 @09:13PM (#43384224)
Several programming languages can testify to the fact than a Benevolent Dictator For Life is not a panacea. Several more than testify that having a Committee to design the language is likewise not a panacea. Perhaps uniquely C++ can clarify for us that both is in fact worse than either alone.
Re:A Guide to Undefined Behavior in C and C++ (2010) by pjmlp on Monday March 17, 2025 @04:14AM (#43386205)
Same applies to C.
Re:A Guide to Undefined Behavior in C and C++ (2010) by tialaramex on Monday March 17, 2025 @04:27AM (#43386259)
Do you see Brian and Dennis dominating WG14 meetings? Nope. They moved on, Bjarne Stroustrup never did. After his initial prototypes and his first book about C++ he's written lots more books and papers, he's lectured classes, he's given huge numbers of talks, all of them about his baby, C++. If you ask WG21 people directly they'll insist he's just one vote (ah yes, JTC1 consensus "voting") but for example WG21 says it will heed the "advice" of its Direction Group, a self-selecting handful of people which is dedicated to following advice from a book written by Bjarne and weirdly always giving exactly the same advice as Bjarne, which makes sense because its most notable member is Bjarne but this advice is signed "The Direction Group" ...

It's like being surprised that the UN Security Council keeps making decisions which favour Russia.

Re:A Guide to Undefined Behavior in C and C++ (2010) by pjmlp on Monday March 17, 2025 @04:39AM (#43386307)
It doesn't change the fact C is equally a design by committee language with all the negativity it entails.

In fact, WG14 very clearly has acted against Dennis when he submitted papers that could have improved C's safer.

Maybe his fat pointers proposal was not good enough, but apparently is wasn't something worth improving upon either.

C authors indeed moved on, first with Alef (which granted had a few design issues), Limbo and finally Go, as C as being driven by WG14 was no longer their thing, C on Plan 9 isn't even C89 compliant.

Re:A Guide to Undefined Behavior in C and C++ (2010) by steveklabnik on Sunday March 16, 2025 @08:33PM (#43383993)
Safe Rust has no undefined behavior. Unsafe Rust does.
Re:A Guide to Undefined Behavior in C and C++ (2010) by vlovich123 on Monday March 17, 2025 @01:41AM (#43385487)
cough std::env::set_var cough :D.
Re:A Guide to Undefined Behavior in C and C++ (2010) by whytevuhuni on Monday March 17, 2025 @03:18AM (#43385932)
std::env::set_var [1] has already been changed to unsafe in the 2024 edition of the compiler [2].

So yeah, such things exist, but what's important is what the compiler devs choose to do once such issues are found. The C++ compiler devs say "That's an unfortunate case that cannot be fixed." The Rust devs say "That's a bug, here's the issue link."

[1] https://doc.rust-lang.org/std/env/fn.set_var.html

[2] https://doc.rust-lang.org/edition-guide/rust-2024/newly-unsa...

Re:A Guide to Undefined Behavior in C and C++ (2010) by vlovich123 on Monday March 17, 2025 @09:55AM (#43388646)
Yes I know all that. Just pointing out that “safe” Rust in practice can have unsoundness because of unsoundness in the underlying implementation. And yes it can be fixed but it did take quite a while to fix this one unfortunately (not that marking it unsafe meaningfully changes things)
Re:A Guide to Undefined Behavior in C and C++ (2010) by steveklabnik on Monday March 17, 2025 @11:40AM (#43389680)
"software has bugs" isn't a particularly interesting thing. The point is, safe Rust has no UB. If mistakes are made, they're fixed.
Re:A Guide to Undefined Behavior in C and C++ (2010) by vlovich123 on Monday March 17, 2025 @12:49PM (#43390423)
I’m not arguing that purely Safe Rust has UB theoretically and I’m 100% sympathetic to the difficulty. I’m saying in practice unsoundness can creep in from the real world and even the std library is not immune from this. This is even ignoring unsoundness due to compiler bugs which are smaller issues for now (but will become more so as ecosystems lag on updating the compiler).

It doesn’t hurt anything to acknowledge that safe Rust can be unsafe due to mistakes in abstractions while simultaneously acknowledging that Rust still has orders of magnitudes fewer memory safety issues than c/c++ even with these problems.

As for this specific bug, this kind of bug took a long time to fix for what it’s worth since it can take up to 3 years for a new edition to allow for fixing it. And “fixing” it doesn’t actually fix the unsoundness in existing code - it just changes the responsibility of who’s supposed to validate the usage is safe. It basically shifts the “blame” to the user for holding their tool wrong because code patterns that had been documented as being sound are now documented as being unsound and the user has to figure out how to make it safe once more.

I’m not trying to cast blame or aspersions - mistakes happen and that this was dealt with shows the strength of Rust’s ability to solve these problems vs c++ which is hopeless. But pretending like safe Rust exists purely in a vacuum devoid of interaction with the real world isn’t helpful I think.

I say all this with the utmost respect to your expertise and we basically agree on a lot of rust-related things. I just disagree slightly on the messaging here.

Re:A Guide to Undefined Behavior in C and C++ (2010) by steveklabnik on Monday March 17, 2025 @01:02PM (#43390520)
> we basically agree on a lot of rust-related things.

I suspect we do too!

> It doesn’t hurt anything to acknowledge that safe Rust can be unsafe due to mistakes in abstractions

I think that the core disagreement here is not that I think that it's harmful, it just seems incredibly banal to me. That is, like, of course it can! So bringing it up feels like an attempt at a "gotcha" that's not really a gotcha.

Re:A Guide to Undefined Behavior in C and C++ (2010) by ultimaweapon on Monday March 17, 2025 @03:10AM (#43385888)
To be fair the UB caused by this function come from the underlying C implementation and this function already marked as unsafe on 2024 edition.
Re:A Guide to Undefined Behavior in C and C++ (2010) by almostgotcaught on Sunday March 16, 2025 @09:24PM (#43384295)
you realize UB is basically an escape hatch from the standard for compilers right? it's not like a flaw in the language, it's gaps negotiated by the standards committee (well for the most part i guess). so the reason new languages don't have UB is because new languages don't have multiple implementations (go definitely doesn't, does anyone use rust-gcc?).
Re:A Guide to Undefined Behavior in C and C++ (2010) by Dylan16807 on Sunday March 16, 2025 @09:34PM (#43384347)
You only need implementation-defined behavior to grease the wheels of multiple implementations. You don't need the gaping void of undefined for that use.

There's a big difference between "it'll be some number, not promising which one" and "the program loses definition and anything can break, often even retroactively".

Re:A Guide to Undefined Behavior in C and C++ (2010) by almostgotcaught on Sunday March 16, 2025 @09:38PM (#43384368)
Potato potato. My point is UB isn't an accident it's intentional. Mind you I'm not saying it's great, just that it's not some kind of slipup.
Re:A Guide to Undefined Behavior in C and C++ (2010) by maxlybbert on Monday March 17, 2025 @12:05AM (#43385106)
"Implementation defined" and "undefined" are different things.

On my laptop, sizeof(long) is 8; that's implementation defined. It could be different on my phone, or my desktop, or my work laptop.

Undefined means, roughly, "doing X is considered nonsensical, and the compiler does not have to do anything reasonable with code that does X." In "Design and Evolution of C++," Stroustrup says that undefined behavior applies to things that should be errors, but that for some reason the committee doesn't think the compiler will necessarily be able to catch. When he came up with new ideas for the language, he would often have to choose between making a convoluted rule that his compiler could reliably enforce, or a simple rule that his compiler couldn't always give a sensible error message for.

For instance, the original compilers relied on the system's linker. If the compiler could interact with the linker, it could perhaps detect violations of the One Definition Rule ( https://en.cppreference.com/w/cpp/language/definition ), but since the linker might have been written by a completely different company, and it's acceptable for different source files to be compiled by different compilers (and even be written in other languages -- https://en.cppreference.com/w/cpp/language/language_linkage ) and put together by the linker, and it's common for binary libraries to be sold without source, there's no guarantee that the compiler will ever have the information necessary to detect a violation of the One Definition Rule. So the committee says that violations create a nonsense program, which isn't required to behave in any particular way.

Re:A Guide to Undefined Behavior in C and C++ (2010) by Dylan16807 on Monday March 17, 2025 @01:04AM (#43385361)
Do you think my last sentence is describing things incorrectly? I don't really understand how you could take that depiction and call it "potato potato".
Re:A Guide to Undefined Behavior in C and C++ (2010) by wolvesechoes on Monday March 17, 2025 @04:53AM (#43386397)
"go definitely doesn't"

What? gccgo, TinyGo, and GopherJS.

Re:A Guide to Undefined Behavior in C and C++ (2010) by porridgeraisin on Monday March 17, 2025 @03:47PM (#43392088)
More prominently, microsoft go
Re:A Guide to Undefined Behavior in C and C++ (2010) by pjmlp on Monday March 17, 2025 @04:13AM (#43386197)
Older languages as well, those that weren't a copy-paste from C with extras.

Modula-2, Ada, Object Pascal, Eiffel, Delphi,...