5 ms·
Unsafe Rust is harder than C
- maxk42 2y agoSafe rust is harder than C.
- Cyph0n 2y agoSafe C is harder than safe Rust.
- Quothling 2y agoZig is easier than Rust.
- jsheard 2y agoSafe Zig is harder than safe Rust, but easier than safe C. In conclusion, programming is a land of contrasts.
- eikenberry 2y agoI've never heard the opinion that safe Zig is harder than safe Rust. Pretty much always the opposite, that Zig is easier than Rust all around.
- binary132 2y agoI think the claim here is that it’s hard to write really safe zig
- kelnos 2y ago> but easier than safe C Well, everything is easier than something that doesn't exist.
- tonetegeatinst 2y agoDosnt GCC have flags that enforce memory safety? Also don't fuzzers handle this issue?
- kstrauser 2y agoIt cannot possibly. You can catch some low hanging fruit, but asking a compiler to evaluate whether a specific chunk of code is memory safe is basically solving the halting problem.
- jmkr 2y agoCan you explain what that low hanging fruit is (or refer me to docs), and also explain it being a decision problem a bit more thoroughly. I will accept that if you have to run a program to decide if it's memory safe then that fits the criteria, but from my understanding static analysis doesn't run the program, and a compiler is parsing and lexing anyway so it should be able to catch at least some things (the low hanging fruit)? Since I have actually started using C I realized how easy it is to be lazy and not handle memory right so it makes Rust and maybe C++ seem more appealing, but trying to figure out random segfaults it seems like address sanitizer and valgrind catches more than I would have assumed is a low hanging fruit. I guess I should look more into how Rust manages that safety or understand what memory safety is trying to accomplish more formally. I've taken GC for granted for years until I needed to care about memory.
- steveklabnik 2y ago(Not your parent) An example of low hanging fruit is -fwrapv. This flag takes a behavior that is undefined, signed overflow, and converts it to defined behavior, two's compliment wrapping. That improves safety, but it does not prevent all errors. There are many flags like this, but they all tackle individual aspects of the problem, and even if you turn them all on, there are situations which aren't caught.
- jmkr 2y agoThanks. Yeah that makes sense for low hanging fruit. Going through the gcc flags it does seem like a lot of tradeoffs have to be made so you can't cover everything. A quick look through compiling Rust it seems it does at least some of this checking at MIR. I'll have to read more about it.
- nanolith 2y agoThat used to be true, but now we have reasonable model checking tools for C. It's possible to write safer C without the cognitive load of Rust. https://www.cprover.org/cbmc/ https://www.cprover.org/cbmc/
- OtomotO 2y agoGreat now give me tooling of this millenium (no, I am not going back to vendor everything manually and I am not reinventing every basic data structure I wrote in University in ever project I work on) and we have a deal! Oh, also get rid of header files, they are archaic. And I want fearless concurrency... And sum types!
- nanolith 2y agoIf you want those things, you don't want C. Pick a reasonable higher level language you like that makes those decisions for you. My comment was not to imply that somehow C is superior to X, Y, or Z, but rather to point out that the safety problem with C does have a practical solution.
- OtomotO 2y agoFair point, sorry (non native speaker here, for what it's worth) have a wonderful day!
- Cyph0n 2y agoI am sure it is “possible”, but we are talking about practicality here. Why doesn’t the Linux kernel embrace model checking instead of experimenting with Rust?
- nanolith 2y agoIt is quite practical. I'm actually planning a book on the subject. The reason why some Rust enthusiasts have been experimenting with Rust in the Linux kernel is because they are passionate about Rust, and kernel maintainers are looking to find younger people. It's neither an endorsement of Rust nor an argument against model checking in C. The reality is that this tooling isn't yet well known about. As it becomes better known, it will be adopted.
- lomase 2y agoAny kind of Rust is harder than safe C#.
- rowanG077 2y agoIs that really the case? I would say writing bug ridden C is easier then Rust in some cases. Writing working C is much harder then writing safe Rust.
- _bin_ 2y agoMaybe this depends on the application type. I've written a lot of each, and maintaining anything involving concurrency is worlds easier in Rust, since those tend to be the most painful and time-consuming bugs to fix. It's got a learning curve, isn't a particularly easy language, and a big chunk of the "community" sucks, but most of the places I've applied it have been a net hassle savings.
- twoodfin 2y agoComing from a position of extreme Rust ignorance & C++ brain poisoning: Here’s the issue: waiting_for_elements is a Vec<Waker>. The channel cannot know how many tasks are blocked, so we can’t use a fixed-size array. Using a Vec means we allocate memory every time we queue a waker. And that allocation is taken and released every time we have to wake. Why isn't a structure that does amortized allocation an option here? I appreciate the design goal was "no allocations in steady-state", but that's what you'd expect if you were using C++'s std::vector: After a while the reserved space for the vector gets "big enough".
- maxbrunsfeld 2y agoI had the same question. I would think that with rust’s Vec, no allocation would occur at steady state. Vec does not automatically resize when removing elements.
- makapuf 2y agoYup, you can even pre-allocate a given vec capacity to not start zero-sized.
- chadaustin 2y agoI'm sorry, I had a whole section on amortized allocation in a draft version of the post but I deleted it, thinking it was tangential. You're not the first person to ask: https://www.reddit.com/r/rust/comments/1gbqy6c/comment/ltonql2/ https://www.reddit.com/r/rust/comments/1gbqy6c/comment/ltonq... And my response: https://www.reddit.com/r/rust/comments/1gbqy6c/comment/ltpv0de/ https://www.reddit.com/r/rust/comments/1gbqy6c/comment/ltpv0... One typical approach is double-buffering the allocation but it doesn't work here because you need to pull out the waker list to call `wake()` outside of the mutex. You could try to put the allocation back, but you have to acquire the lock again. I had an implementation that kept a lock-free waker pool around https://docs.rs/wakerpool/latest/wakerpool/ https://docs.rs/wakerpool/latest/wakerpool/ but now you're paying for atomics too, and it felt like this was all a workaround for a deficiency in the language. Intrusive lists are the "correct" data structure, so I kept pushing.
- deleted 2y ago
- melodyogonna 2y agoRust is harder than C
- OtomotO 2y agoTo me C is much, much harder than Rust. I've written both, albeit way more Rust.
- melodyogonna 2y agoWhat makes C much much harder? What concepts exist in C and are not present in Rust?
- OtomotO 2y agoIt's not about concepts, it's not about language constructs but the overall work and mental load working with the languages. For me it's header files, no package manager, doing pointer magic all the time (void pointers are... Brrr!), concurrency, ... I could go on. I don't enjoy it, although I like simple and easy things. C is simple, but not easy
- uecker 2y agoI find the mental load in C very light and I rarely use a void pointer in C. I also like headers, they give a clean separation of implementation and interface and enable very fast compilation.
- gauge_field 2y agoIt all depends on what kind of project you work on. I work high performance libraries, when I compare the code C and Rust, the void is used alot of blas libraries, to dispatch different function with different type information. They also include reimplementation of threading libraries that you find as a function from a crate. This coupled with lack of doc.rs, header files, (C not having namespaces/modules (especially for complex projects)) my needed cognitive load is higher for C than for Rust. Non-negligible amount of these libraries are also hard to setup on non-unix environment (mainly due to not having OS-independent build system). One of my favorite things is looking at rust cli projects, checking them and install them with cargo install $(name_of_project) and have it working. Also, alot of other stuff is not default (e.g. for testing, you just #[test] in rust, for C you need 3 party tooling). The more complex project becomes, the more of these needs you realize. Some of these you might need or not, it all depends on your case. But, for myself (someone also used to other more modern tooling system), these do matter to a non-negligible extent.
- handwarmers 2y ago[flagged]
- whatshisface 2y agoIf you aren't nice to rust people, they'll get RCE after overflowing your buffers and make you a furry.
- deleted 2y ago[deleted]
- f1shy 2y agoThey come with the book in their hands... oh... convert or be burn in the fire!
- dgfitz 2y agoFor me, it really is just so much syntax and mental overhead to track. Somehow it seems like the same goals could have been accomplished with less verbosity. It almost feels like an engineering tool/language, by devs for devs, instead of by devs for “customers” where customer == “outside” devs, of which I am one. Edit: typo
- wongarsu 2y agoUnsafe Rust is significantly harder than C, with complex rules that are not fully specified. But luckily you don't have to write a lot of it. And the bit you need can either come from battle-tested libraries or be contained to it's own module where you can rigorously test and fuzz it. And the tooling available for that is pretty good. The article shows good examples of that. There is some work on making unsafe rust safer, or at least easier to get right. But those are significant undertakings that will take years to pay off. On the other hand safe rust is so much easier than correct C that I don't particularly mind the tradeoff.
- kazinator 2y agoSafe Rust looks absolutely painful painful compared to other safe languages. Correct C is not actually hard to write. It can be somewhat hard to convince oneself that it's right. That's an important difference. Not all C has to be correct. If it's experimental or exploratory code that'll be thrown away. If that just works on one machine or on particular inputs that you care about, or it only certain specific environmental conditions, that can be fine. Correctness is more than just memory safety and avoiding overflows. They are still bugs in programs and languages that avoid those problems.
- tptacek 2y agoWhen people talk about not needing to write much unsafe Rust, they mean that in any large-scale system, there are probably only a couple hotspots that are complicated enough to need the escape hatch from the Rust safety rules; you write the unsafe code, you give it an interface to the rest of the code, you carefully validate the unsafe code, and you're good to go. They don't mean that you write unsafe Rust code for experimental or exploratory code that will be thrown away. You could do that, but it's not common. More importantly: this approach of parsimoniously writing unsafe code in a larger-scale safe system does not work in C/C++. Memory safety issues can (and do) crop up all over your system, not just in the small "unsafe" parts you validate carefully.
- steveklabnik 2y ago
- kelnos 2y agoIt sounds like this boils down to one thing: C and Rust have different aliasing rules, with Rust's being much more restrictive. You can't assume programming in unsafe Rust is like programming in C. Unsafe doesn't mean "do whatever you want"; it means you get to do things that the compiler won't check for you, but it's your responsibility to ensure you're still maintaining Rust's invariants. So yes, unsafe Rust is harder than C. I think that's fine, though. Most people will be able to get by without writing any unsafe Rust, and those who still need to use it will end up writing very little of it. And tools like MIRI exist to help increase your confidence that your unsafe Rust is correct.
- jsheard 2y ago> C and Rust have different aliasing rules, with Rust's being much more restrictive. Rust is more restrictive by default, but C's restrict keyword lets you opt-in to strict aliasing semantics in exchange for unlocking compiler optimizations that would otherwise be unsound, so it's not like you're free from having to think about aliasing in high performance C code.
- kelnos 2y agoAgreed, but in practice defaults do matter, and it's pretty rare that I see a C code base that actually makes use of 'restrict' etc. It's nice to see it sprinkled liberally throughout glibc's headers, but that's the exception, not the rule.
- physicsguy 2y agoIt’s in pretty much every simulation code base I’ve worked on (both academic + industry)
- steveklabnik 2y agoIt's not so much "more restrictive" as it is "just plain different." You have behaviors for all four quadrants: there's stuff that's okay in Rust and not okay in C, stuff that's okay in both, stuff that's not okay in both, and stuff that's not okay in Rust and is okay in C.
- andrewmcwatters 2y agoI feel a sort of professional obligation to learn the cryptic unnecessary glyphs and runes that Rust and its ilk proliferate all for this important concept that is memory safety. However, I would much rather that more languages like Go and Zig simply take off in popularity instead, and that we just reject the eyesore and cognitive mess that is Rust syntax. It’s a language which has no regard for beauty.
- jcrites 2y agoFor what it's worth, I disagree. I think it would be difficult to design a language more elegant than Rust while accomplishing the same goals. Maybe those goals aren't ones that everyone cares about, and that's OK. It's a language that's definitely worth learning; it expands the mind in a way that languages like Go (or Java, or any GC language) will not. There is a great beauty and elegance to its design.
- OtomotO 2y agoI would love a much simpler Rust...a Zig with a borrowchecker, a small stdlib (like Rust), some official package manager. I agree that Rust has a lot of syntactic warts but the common stuff I find beautiful
- MarkSweep 2y agoAs long as we counting Go as an alternative to Rust, there are a whole host of other garbage collected languages that provide memory safety benefits compared to the status quo of C and C++. Languages like Ruby, Java, Python, C#, and PHP. Personally I don’t think it makes sense to write all software in Rust. A GC makes it much easier to write certain patterns that are frustrating to write in Rust.
- fjasdyfs 2y agoI agree the syntax in Rust can be hairy however presenting Go as an alternative to Rust makes zero sense. They have completely different runtime characteristics and goals.
- sgt 2y agoCan't wait for Swift to gain traction in systems programming.
- agentultra 2y ago> Using a Vec means we allocate memory every time we queue a waker. And that allocation is taken and released every time we have to wake. Is that so? On every push back? I’d expect it’d only do an allocation when the current array segment is almost full… as a vector you might write by hand or like the ones in the C++ standard libraries do.
- raptorfactor 2y agoThis surprised me too, so I checked: https://doc.rust-lang.org/std/vec/struct.Vec.html#capacity-and-reallocation https://doc.rust-lang.org/std/vec/struct.Vec.html#capacity-a... "Vec does not guarantee any particular growth strategy when reallocating when full, nor when reserve is called. The current strategy is basic and it may prove desirable to use a non-constant growth factor. Whatever strategy is used will of course guarantee O(1) amortized push." Seems it should be amortized just like in C++?
- agentultra 2y agoI don't want to tell the Rust folks what they should do but as a potential user I'd be more interested in the language if it was explicit (or the rules we clear and deterministic at the least). This claim took me a bit by surprise and I'd be upset if I'd encountered it in production code.
- ratorx 2y agoI think explicitly stating what it doesn’t guarantee is the right thing to do. Otherwise, the API becomes tied to your implementation through implicit details, which can prevent future generic performance improvements (e.g. unordered_map pointer stability in C++ prevents the implementation from being changed to a different representation like absl::flat_hash_map, even though that’s a guarantee that most people don’t care about). Re: performance considerations. This is important, but for a performance critical application, any compiler, library etc version change can cause regressions, so it seems better to benchmark often and then tackle this, rather than make assumptions based on implicit (or even explicit) guarantees.
- Sytten 2y agoMost of the complexity comes from the fact that all types are moveable by default. That is why I prefer this proposal to make it opt-in [1]. Working with pin really sucks the joy out of you and it won't be some sugar syntax (the current &pin mut proposal) that will help that. Rust is a fine language most of the time, but sometimes like the author you fall in rabbit holes. [1] https://smallcultfollowing.com/babysteps/blog/2024/10/14/overwrite-and-pin/?utm_source=atom_feed https://smallcultfollowing.com/babysteps/blog/2024/10/14/ove...
- codewiz 2y agoThe very last line: "Putting this in words was as hard as writing the code."