Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Rust unsafe has pretty much the same functionality as plain C, with more vervose syntax. So I would expect this model to refuse to give any examples of C code whatsoever.


C is a much simpler language, so it's far easier to reason about the semantics of "unsafe" code.

For example: Rust has destructors (Drop trait) that run automatically when a value goes out of scope or is overwritten. If memory for a struct with a Drop trait is manually allocated (and initialized with garbage) and it is assigned to, the `drop()` method will run for the previous value of it which will cause undefined behavior.

That's just one feature: Rust also has references, tagged unions, virtual method calls (&dyn Trait), move semantics, `Pin<T>`, closures, async/await, and many more, all of which make it harder to reason about safety without the guardrails provided by the language for regular, "safe" code—for which barring a compiler bug it is actually _impossible_ to shoot yourself in the foot like this.

This is actually why it's so incredibly hard to write C++ code that is provably correct: It has even more features that could cause problems than Rust, and is _always_ in "unsafe" mode, with no guardrails.


gcc C has destructors (cleanup attr), nested functions/closures

you can do tagged unions with cpp tricks, and so-on

(sadly I have seen most of these used...)

regardless, what makes C hard is undefined behaviour


Not entirely true. You can't bypass the borrow checker for example, and you have to maintain Rust invariants when you use it. Hence the name.


To be fair, C is basically one giant footgun…


Yawn. This is such a tired trope.


Is it not true, though? Is there some other language that has a list of banned (commonly used) functions[0] in a major project?

[0] https://github.com/git/git/blob/master/banned.h




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: