this post was submitted on 30 Nov 2023
-2 points (40.0% liked)
C++
1773 readers
3 users here now
The center for all discussion and news regarding C++.
Rules
- Respect instance rules.
- Don't be a jerk.
- Please keep all posts related to C++.
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
This blog post writes a dissertation about garbage collection, heap memory management, the absolute need to take courses on assembly language, and other contrived and absurd tangents.
Looking at the code, the guy gets a double-free because he instantiates two
std::unique_ptr
from the same raw pointer.I'm sure the author felt very clever to pull up all these topics to write a blog post about, but in the end all they're doing is writing buggy code based on their misconception of a topic.
You can call it writing buggy code based on misconceptions, but the fact that it's possible (and not even especially difficult) to misuse smart pointers badly enough to produce program crashes and undefined behavior is still a fundamental weakness of C++ as a language.
As a counterexample, this type of bug is impossible to produce in Rust without explicitly using the
unsafe
keyword, and that keyword is something that is almost never used by regular developers and is an easy thing to audit for.Edit: That being said, if you're stuck using C++ then obviously using smart pointers is the right thing to do whereas using raw pointers and managing the memory yourself is completely asinine, so if the author's point is to not use smart pointers in C++ then I suppose they want you to just... Leak memory? Because if you're able to figure out where it's safe to free a raw pointer, then you're able to figure out how to correctly use a smart pointer in that situation.
I agree with what you're saying even though I do think a lot of C++'s bad rep comes either from C or from pre-C++11 code. I also think that modern code should include clang-tidy in the CI, and if so at least simple mistakes like in OPs code would be flagged with "warning: Use of memory after it is freed [clang-analyzer-cplusplus.NewDelete]"
https://clang-tidy.godbolt.org/z/8E169bons
Note that all of the warnings in there are valid and should be fixed, so it's not like wading through a see of false positives. That being said, the post is interesting in its explanation of why the example does what it does. Too bad all of the other stuff in there is bonkers.
Linters are good and should absolutely be used in any serious C++ project, but they can only catch the most basic sources of UB. I almost never make a mistake that a static analyzer can catch. It's the multithreaded lifetime issues and data races that ambush you the hardest, and I don't see any way a C++ static analyzer could hope to catch those.
But yes, most of the original post is bonkers and has the totally wrong conclusion.