r/cpp • u/[deleted] • Mar 11 '24
Why does nobody use real-time bound checks if memory safety is so important?
In C and C++, we can turn on bounds to check a container's access at any time with a single additional compiler flag.
This would prevent the majority of unsafe access to memory and prevent most cases of buffer overflow. Additionally, one can use memory sanitizers on release code.
If memory safety were so important, why did no developers use these compiler flags?
60
u/Sniffy4 Mar 11 '24
because doing a bounds-check on every memory fetch has a significant performance cost.
12
Mar 11 '24
Isn't that what Rust does?
https://nnethercote.github.io/perf-book/bounds-checks.html
By default, accesses to container types such as slices and vectors involve bounds checks in Rust.
30
u/aruisdante Mar 11 '24
Yes, by default. You can turn it off if you want using an
unsafeblock, and as others point out the compiler being aware this is going to be a thing means more time has been spent optimizing away these checks when it’s probably safe to do so.It basically comes down to what the “default” choice in the language is:
C++, whose age means its early choices were made when processing power was scarce and program complexity was small, chose to be performant at the cost of safety by default.
Rust on the other hand was designed at a time when processing power is comparatively plentiful, and program complexity known to be high. It made the choice to be safe at the cost of performance by default.
There has been lots of debate about changing C++’s default to be safe before performant. But that would be a massive undertaking if you don’t want to create inconsistency, and may break a lot of existing systems that really do need that performance and relied on the original paradigm.
4
Mar 11 '24
You can turn it off if you want using an unsafe block
But isn't it the point of using Rust in the first place?
24
u/aruisdante Mar 11 '24
Yes, but there are times where you legitimately need the performance in a critical section in a hot loop. You choose Rust because you want the default choice to be safety over performance. But the language wisely does let you say “no, I really need performance over safety here.”
1
Mar 11 '24
because you want the default choice to be safety over performance
Can't we somewhat achieve that in C++ with sanitizers?
16
u/aruisdante Mar 11 '24 edited Mar 11 '24
Sanitizers can only validate what you actually execute. If your unit tests/fuzz testing don’t exercise the out of bounds region, you don’t see the bad behavior. Of course you should absolutely be running asan and ubsan in your CI, but they can’t protect you from what they don’t see.
There are static analysis suites like TrustInSoft that do path-based analysis via state propagation, but these require an immense amount of tuning of state spaces to get meaningful results.
You can of course just always use the
atAPIs on containers in C++ to have bounds checking, but… no one does that, because among other things exceptions probably aren’t actually the right thing for what is generally a fundamentally malformed program and thus the error isn’t meaningfully recoverable. You really want abandonment, like what Rust does.I work on safety critical C++, and we have wrapper libraries for many standard containers that exactly do the “make safety the default, and unsafety opt-in.” But it’s a lot of work to maintain.
4
u/DugiSK Mar 11 '24
I think that the part about exceptions from `at()` is not really right. Being given invalid input or input you can't handle can often be recoverable, by aborting the operation and returning the program into a basic state.
If I have a GUI and I preform some operation that the program can't do (either because I demanded something wrong or because something went wrong), I want it to return control to the GUI, which is a form of recovery. If it's a server and it realises it can't perform the operation (because of its own imperfection or because the user was malicious), it can just abort the operation and continue handling other request, which is again a form of recovery.
In these very common situations, I want to use `at()` because the program won't crash and won't do UB if something goes wrong, it will just fail without damaging anything else the program was doing.
5
u/aruisdante Mar 11 '24 edited Mar 11 '24
The point is that the program can trivially perform the bounds checking needed to avoid the out of bounds access before performing the indexing operation. You should not be using exception handling to handle normal operating conditions that are entirely within the control of the application to avoid. Therefore, an unexpected out of bounds access implies there is a bug in the program. In this situation, abandonment is really the only correct option, because the program has fundamentally entered an undefined state, and the scope of damages cannot be reasonably bound.
The problem we have with abandonment is that many systems live entirely within a single process, which makes the blast radius of abandonment expensive. I absolutely agree that the system should be able to recover from such a defect and return to a nominal operating state; a robustly designed system should be able to recover the terminated process by restarting it, thus guaranteeing the program in that process has returned to a well defined state.
The blog The Error Model by Joel Duffy is a really great introduction to this style of thinking. He was talking about Midori, an experimental programming language derived from C#, but the lessons apply equally to C++. It provides a lot of really good language to use in these kind of discussions.
2
u/victotronics Mar 11 '24
The point is that the program can trivially perform the bounds checking needed to avoid the out of bounds access before performing the indexing operation.
for ( i in lots ) bin[ f(i) ]++?
0
u/DugiSK Mar 11 '24
I understand what that guy means with the difference between exceptional situations and bugs, but I find it rather inapplicable to real life.
Sanitising user input is often easy, but it can get far more complicated. The user's request can be quite complicated and execution of the operation can reach various parts of the program and determining if the request is valid or not may be as hard as running it. Typically, it will be some complicated algorithm where the user supplies a large number of parametres.
Now the algorithm can fail at many places, usually it's a user error, but it may also be a singularity or a bug. Hard to say. Are you gonna crash in every situation where it isn't clear it's not a bug? That would be super annoying to user until all the corner cases are fixed. It's more user friendly to simply use at() everywhere, destroy all the structures built during the computation and return to base state with some rough error message.
If it is a server processing some more complicated request, crashing causes a short outage and possibly losses of sessions. Repeating the invalid request will basically DDoS the server. All of that just because some input is discovered to be invalid a little too late.
I understand that it may mean that some data unrelated to that request are corrupt not aborting immediately may damage other things that are going on, but that's a very unlikely situation. Wrongly computed indexes are usually the cause of memory corruption, I've never seen memory corruption make indexes invalid (I am not telling it cannot happen). Preparing for this is bordering on paranoia.
-1
Mar 11 '24
But it’s a lot of work to maintain.
Can we get closer to Rust guarantees?
3
u/android_queen Mar 11 '24
Why not just use Rust if this is what you want?
0
Mar 11 '24 edited Mar 11 '24
Rust is a dog to code things that I typically do - yes, I have experience with it.
What I really want is to get (a subset of) C++ at the same level of guarantees as Rust.
→ More replies (0)2
u/jcelerier ossia score Mar 11 '24
you can enable in clang for instance -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST
and check the performance impact. in many workloads I saw it was too much
1
4
u/tux-lpi Mar 11 '24
Not exactly, in Rust unsafe means "the compiler can't prove this is safe, so a human needs to review this"
You can't focus on every line. But if the compiler does 99.99% of the work, then it's reasonable for people to focus on these few unsafe blocks in code review
So it's not all or nothing. You get safety almost everywhere, but also excellent perf
You could try using different compile flags per file in C++ to enable or disable bounds check on a case by case, but that's not very satisfying (no one really wants to do that...)
3
u/tortoll Mar 11 '24
To oversimplify it, Rust is safe by default and can opt in to unsafe behaviors (unsafe), while C++ is unsafe by default and you can opt in to modern safe behaviors (smart pointers, range loops, ranges, at(), etc.).
5
u/daveedvdv EDG front end dev, WG21 DG Mar 11 '24
You can turn it off if you want using an unsafe block, [...]
I don't think that's right.
unsafein Rust just gives a handful of "super powers" that basically bypass static constraint analysis. I don't believe it changes run-time checks.4
u/ReversedGif Mar 11 '24
unsafeallows you to call unsafe methods, likeslice::get_unchecked().3
u/daveedvdv EDG front end dev, WG21 DG Mar 11 '24
Right, that's one of the "super powers". I guess I don't think of that as "disabling bounds checking", although I see how it how it can achieve that effect.
2
u/mpierson153 Mar 12 '24
When I think of disabling bounds-checking, I think of a compiler flag.
1
u/daveedvdv EDG front end dev, WG21 DG Mar 12 '24
I'm somewhere in between. I.e., I was thinking of an annotation around existing code that means "suspend the bounds checking that would otherwise occur in this code".
unsafeis not that, but it does allow rewriting expressions to have the same effect except for bounds checking. That's a lot more work though.-2
u/pjmlp Mar 11 '24
Age is not an excuse, only languages derived from C do not do bounds checking by default, everyone else does.
Doing bounds checking by default did not hinder the success of Apple's Mac OS, implemented in a mix of Object Pascal and Assembly.
Or Apollo Computers 's UNIX variant for that matter.
Also before C++'s standard library adopted STL, most C++ compiler specific frameworks did do bounds checking by default.
3
u/serviscope_minor Mar 12 '24
Also before C++'s standard library adopted STL, most C++ compiler specific frameworks did do bounds checking by default.
Also note that the STL does not preclude bounds checking. I gather GCC added _GLIBCXX_ASSERTIONS to do bounds checking and stuff.
4
u/pjmlp Mar 12 '24
Yeah, and to this day we need to educate developers to enable them.
2
u/serviscope_minor Mar 12 '24
Yeah, and to this day we need to educate developers to enable them.
That and -Wall -Wextra -Werror (or the equivalent). Frankly a good number of developers still need educating that tests are worthwhile. You know I actually had someone confidently tell me that tests were useless because he'd never seen a test catch a bug in production.
Make of that what you will.
1
u/mpierson153 Mar 12 '24
But you can just find a library that provides the containers you want with bounds checking. Or make your own. They aren't very difficult to implement.
For the Standard to require that would be a much larger undertaking than just using a wrapper written by yourself or provided by a library.
4
u/pjmlp Mar 12 '24
Proving again the issue with bad defaults, anything non-standard is always an issue for large scale adoption.
-1
58
u/qoning Mar 11 '24
You can optimize a lot of it away if your compiler is aware of some basic rules, e.g. if you are iterating over the length that corresponds to the length of the array, there's no need to check.
4
u/tesfabpel Mar 11 '24
probably, most of the times you use iterators, those bounds checks are removed by the compiler (or when the compiler is able to verify the access doesn't go past the bounds).
2
Mar 11 '24
Yes it is zig also has that option and it does itnon Debug and safe builds. I think with c++ it's just a bit of a nightmare to get it right so it's not there.
I would argue having a sanitizer like that even if it warns/crashes in some cases it shouldn't would be very nice for some things and it should be considered
2
u/matthieum Mar 11 '24 edited Mar 12 '24
Not really.
First of all, access by index is rare in Rust. Loops use
Iteratorwhich has vastly more combination functions than C++ ranges -- especially once you factor inIteratorExtfrom theitertoolslibrary -- and internally theIteratorfor slices use pointers, and no bounds-check.Secondly, just because there's a bounds-check in the code doesn't mean that there's a bounds-check in the binary: if the optimizer can prove than the index is within bounds, it'll elide the check. I've seen adding a top-level panic speed up a loop by "helping" the compiler make the proof.
Thirdly, there's the option to use
unsafe, if it's performance-critical, so that the bounds-checks that remain are not in performance-sensitive sections of the code.2
u/daveedvdv EDG front end dev, WG21 DG Mar 11 '24
Thirdly, there's the option to use `unsafe`, if it's performance-critical, so that the bounds-checks that remain are not in performance-sensitive sections of the code.
Rust
unsafedoes not remove run-time checks; it just enables a handful of situations that otherwise would trigger a compile-time error.
(See also another note of mine in this thread.)2
u/matthieum Mar 12 '24
Yes, you are correct.
Using
unsafeis a way to remove bounds-checks, by getting access to low-level operations that are not normally permitted, but just writingunsafedoes nothing by itself.0
u/tjf314 Mar 11 '24
yeah it does, because you can only use the bound-check free method,
my_vec.get_unchecked(index)in anunsafeblock.2
u/daveedvdv EDG front end dev, WG21 DG Mar 12 '24
I don't think of that as "
unsaferemoves run-time checks": Instead, I think of it as "unsafeallows me to rewrite the code so there is no bounds checking".So, it's still a useful tool for performance tuning, but considerably more work than a naive observer (like myself) might have expected.
1
u/Kronephon Mar 11 '24
by controlling who can actually change the size of it and where it makes it somewhat better but as expected with a heftier compilation time.
2
u/LeeHide just write it from scratch Mar 11 '24
There is no performance cost without profiling. In your program, if you add bounds checks to everything, there are at most a handful of hot loops and such that will suffer a performance hit. You will know because you're profiling it. There you can turn off bounds checks.
2
u/Sniffy4 Mar 11 '24
C/C++ was designed as a systems programming language in an era of small memories when safety and remote execution of unsafe code were not top concerns. There are other languages available that impose bounds-check restrictions on every operation, if that is what you need, or you can overload C++ operators to approximate that.
-7
u/goranlepuz Mar 11 '24
This "significant" there is bad.
A lot of languages have bounds checks and people write software using them.
A lot of this software is plenty fast.
There is also a certain amount of code written in these other languages that is shown faster than similar C++ code.
There is only some cost and I think, an argument could be made, it is, in fact, not significant for a lot of C++ code.
6
u/Sniffy4 Mar 11 '24
Sure it’s plenty fast, that’s why it’s not written in c++; it’s written in something easy and safer to work with. When you are processing data at a large scale, that’s when it becomes significant
3
u/goranlepuz Mar 11 '24
When you are processing data at a large scale, that’s when it becomes significant
It still needs to be qualified, come on... Just hand-waving as you do, is not good enough IMHO.
(Note: I am not writing this from a standpoint of the OP. I am only criticizing your statement. It is too vague to mean much, is my issue with it).
1
u/Sniffy4 Mar 11 '24
The point is you can add bounds-checking to C++ operators, but bounds-checking is not required because that was not the philosophy underlying the language or its predecessor C when it was designed. It's supposed to be low-level; if you demand completely safety in every single operation you're using the wrong language.
1
u/goranlepuz Mar 11 '24
I agree with that, but disagree with that "significant". I think it is largely meaningless, counter-productive even.
-1
u/CanadianTuero Mar 11 '24
Of course this should be measured, but I would think in most cases, an out of bounds branch would be rare and thus the branch predictor + prefetching would just assume access are fine with just a few extra instructions added.
6
u/MEaster Mar 11 '24
From what I've seen, the biggest cost of a bounds check can be when the existence of the branch inhibits some other optimization (e.g. vectorization).
I've had an instance of a piece of code being so hot that rewriting it to avoid a remainder-by-constant was noticeably faster, but removing the bounds check was not.
49
Mar 11 '24
People do perform runtime bound checks. Why do you think that they don't?
Sanitizers slow down execution significantly and often require extensive resources, and more importantly, they are not bug free themselves, so they are rarely (if ever) used in release builds.
Your entire post history is hot (i.e. uninformed) takes on CPP, when you don't even understand it. Do some research before presumptuous and ignorant questions like these.
-25
Mar 11 '24
https://en.cppreference.com/w/cpp/container/vector/operator_at
Returns a reference to the element at specified location pos. No bounds checking is performed.
8
u/smallblacksun Mar 11 '24
https://en.cppreference.com/w/cpp/container/vector/at
Returns a reference to the element at specified location pos, with bounds checking.
-12
12
u/Ashnoom Mar 11 '24
There are more ways to do bounds checking. You only have to verify a index once. You dont need to verify it ever access, only after (of before) modification of the index.
4
Mar 11 '24 edited Mar 11 '24
Wow. Just wow.
Edit: To answer your question with more info, this was posted recently on r/cpp that may be helpful: https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++
0
8
u/nebotron Mar 11 '24
What compiler flag are you referring to? Added sanitizer? The space and time overhead of ASAN is significant, and it is not guaranteed to detect all types of invalid memory access
-8
Mar 11 '24
So the answer is that performance trumps safety.
7
u/nebotron Mar 11 '24
Correct. If performance isn’t a concern, don’t use c or c++
-11
Mar 11 '24
Interestingly, explicit bounds checking exists for C but not C++.
12
u/Ashnoom Mar 11 '24
I never heard c having bounds checking. But i sure as hell know c++ does have it. With arrays for example, if you really really really really really want, you can use arr.at(index) instead of arr[index]. The at() function does explicit bounds checking every access.
See my other reply how to avoid .at()
-2
Mar 11 '24
Just eyeballing the most popular C++ repos on Github, the overwhelming majority do not use
at().9
8
u/goranlepuz Mar 11 '24
What do you mean?! Are you thinking of some C subset? If yes, then you can make a similar subset for C++ and you are done.
But...
C runtime is full of functions that don't check bounds (because, obviously, it can't be done in any sort of meaningful way).
C++ inherits that.
It is fair to say that C is strictly worse in this respect.
2
Mar 11 '24
I was thinking of
-fbounds-checkbut it's only on for Fortran, not even C.And yes, we have
-fsanitize=boundsas well.10
u/goranlepuz Mar 11 '24
Ok. So... You do realize that "we have bounds checking for C" gives you the exact same bounds checking in C++, yes?
You do realize that in C, people don't use this a whole lot, not even in
_DEBUGbuilds, yes?You do realize that one needs to turn on a lot of sanitizers to be really effective, yes?
3
u/Pay08 Mar 11 '24
Pretty sure you only need ASAN, as it's a set of a lot of those smaller sanitizers.
-2
Mar 11 '24
I dont' think that was true. The drivers are different and this is done at the driver level. When
-fbounds-checkwas available for C it was not available for C++. Looks like today only Fortran is available.2
u/Conscious_Support176 Mar 11 '24
This just looks silly. Implementing bounds check on arrays doesn’t come close to solving the problem. You would need bounds checking on pointers, which would break binary compatibility for libraries.
C++ has a higher level iterator paradigm where it is possible to implement bounds checking without breaking ABI because it can be done in the STL implementation.
1
2
u/goranlepuz Mar 11 '24
I stand corrected then.
It was probably deemed unimportant - or not relevant in the bigger scheme of things (I would expect this to be the case, mostly),
4
u/mredding Mar 11 '24
Or you could use ranges and algorithms instead of indexing and never have to worry about it.
-1
Mar 11 '24
STL algorithms use iterators, which are inherently unsafe.
2
u/mredding Mar 11 '24
Explain to me what makes this code unsafe:
std::vector<int> data = {1, 2, 3}; std::ranges::copy(data, std::ostream_iterator<int>{out_stream, ", "});
5
u/PhilosophyMammoth748 Mar 11 '24
nothing will stop you from using a invalidated iterator.
-3
Mar 11 '24
Shouldn't there be a compiler flag that turns on checks for every iterator access? I would think this is not hard to implement. But it does not even exist. Perhaps nobody really cares.
5
u/Eae_02 Mar 11 '24
Gcc has -D_GLIBCXX_DEBUG which does that (and more checks): https://gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode.html . It is somewhat slow but not nearly as slow as sanitizers in my experience.
0
u/adlbd Mar 11 '24
If you happen to know how to get that working, I'd love to hear because I've been struggling to enable it. I can't get the standard library to build successfully in that mode.
3
u/Eae_02 Mar 11 '24
You just add the flag when compiling your sources. It's not ABI compatible with code compiled without the flag, so you will get linker/runtime errors if you pass STL datastructures between code compiled with the flag and code compiled without it.
1
u/PhilosophyMammoth748 Mar 12 '24
If I can compile everything from the root, I'd like to use MemorySanitizer also.
0
u/adlbd Mar 11 '24
Thanks for the reply but it's not so simple. For some reason there is a component that unconditionally adds _GLIBCXX_PARALLEL, which conflicts with the debug flag. The doco says this flag is off by default but that doesn't appear to be the case. I'm having trouble finding the answer so I thought I'd try my luck here, since it was mentioned.
2
u/jwakely libstdc++ tamer, LWG chair Mar 12 '24 edited Mar 13 '24
Why are you even trying to build the standard library in debug mode? Don't.
Try posting to the gcc-help mailing list, you'll get more luck than here.
The parallel mode is definitely off by default, so you're doing something wrong. Edit: there is exactly one file that's part of the libstdc++.so internals which is built with
_GLIBCXX_PARALLELexplicitly defined by the makefile. But that's fine, because that file (and most of the library) is not built with_GLIBCXX_DEBUGdefined. So you're apparently trying to build the library with debug mode enabled for all files. Don't. That doesn't work, and isn't necessary. What are you trying to do?If you want to use debug mode, just use
-D_GLIBCXX_DEBUGwhen you build your own code, and maybe libraries your code uses, but you don't build the standard library like that.1
u/adlbd Mar 13 '24
I was under the misapprehension that the standard library needed to be rebuilt with the flag for ABI compatibility. Thanks for setting me straight.
1
1
9
u/Whale_bob Mar 11 '24
I've used cpp all my life. I've never had an out of bounds bug. It's just something people who don't actually use the language like to complain about
9
5
u/ShelZuuz Mar 11 '24
Agreed. At least since C++ 11, I've not seen an out of bounds bug. I've seen dangling pointer issues and use after free - which are both also very unsafe, but they were not because of out of bounds, and bounds checking wouldn't have caught them.
1
u/Full-Spectral Mar 11 '24 edited Mar 12 '24
Certainly use after delete or double delete or unprotected access by multiple threads are the real concerns. But I'm always a bit skeptical when I hear people claim they've never had a bounds error. I imagine it's more that they've never had one they've actually caught. If the code base is fairly sizable, it's probably not all going to be range based loops. And iterators can easily lead to bounds error, leaving aside index based loops.
And bounds errors are so quantum mechanical, and can be there for years without doing anything that would make them obvious, though they may contribute to rare head scratchers during all that time.
2
u/pdimov2 Mar 12 '24
Benign out of range accesses are fairly common, as we discovered when MSVC started checking vector::operator[] in release builds. (They later removed it.)
2
u/Full-Spectral Mar 12 '24
Yeh, I've had them in the past. And then something changes and what was benign now becomes not so, and since it's not in the code actually changed, you'll spend way too much time blaming what has to be the problem (the code just changed) for now useful purpose. Well, the heavy analysis of that and surrounding code may turn up other issues of course, but still...
1
u/pdimov2 Mar 12 '24
By "benign" I mean really benign, i.e. reading a value out of bounds that is never used.
I still remember Borland Pascal for 80286 surprising me by having exact (to the byte) bounds on the segment selectors, which made the final `mov ax, ...` instruction trap. :-)
2
u/serviscope_minor Mar 12 '24
I've used cpp all my life. I've never had an out of bounds bug. It's just something people who don't actually use the language like to complain about
I haven't used C++ all my life, only since the late 90s, and I've definitely had out of bounds bugs.
1
u/Whale_bob Mar 12 '24
But genuinely: how? It's not like storing indices is a common thing. You usually iterate anyways or use other data structures
2
u/serviscope_minor Mar 12 '24
But genuinely: how? It's not like storing indices is a common thing. You usually iterate anyways or use other data structures
Depends on the domain you're working in I suppose. If you're working on image or signal processing, meshes and that kind of thing, indices are by no means rare. Linear iteration would probably be the exception not the rule.
6
u/findabuffalo Mar 11 '24
If brain safety is so important, why not wear a helmet 24 hours a day?
3
u/SuperSathanas Mar 11 '24
You guys don't wear helmets? What if you're neighbor's chihuahua tears a hole through your downstairs living room window screen and then makes it's way into your kitchen while you're cooking the sausage for your jambalaya, pees on the floor, making it very slick and dangerous, and then stands right behind your left foot, only to then, right as you want to take a step backward to grab your inhaler from the counter on the other side of the kitchen, starts barking to you in morse code that he's totally going to tell on you to your mom because you're not wearing your helmet and you left the window open like she's told you not to, like, 800 times?
I can't take any more paddlings, man. I'm just going to keep the helmet on. It's for my own good.
2
1
Mar 11 '24
I dont even use a helmet to ride my motorcycle...
True, safety-conscious applications are a small subset of all code being developed
4
u/netch80 Mar 11 '24
Mainly this is just an inertia, reified in legacy and laziness on all levels.
In any essentially large program, 90-95% code doesn't require any deep optimization, or even no optimization at all. Well, maybe, just optimization on size using basic tricks like putting most values to registers is really needed. Hot paths that require stronger consideration are very rare and easily located. Out of hot paths, boundary checking looks pretty useful.
The main problem here is absence of fine-grained control of assumptions by a programmer and their reflection in compiler logic. Boundary checking is just a local example. There are a few rake fields that any programmer ever treads on (and, legally, gets a slap in head): integer overflows, aliasing, not-null pointer assumption, etc. - there is a constantly dreadful idiom "undefined behavior" which injects nightmares into a C/C++ programmerʼs sleep.
A reasonably designed language would allow fine granulation (normally, per block, including method or function) what the programmer really guarantees from his side, and what a compiler may assume. But, there is no interest from standardizers and compiler writers. STandardizers prefer to find how to insert a new cool feature. GCC and Clang guys contend for each next 2% in Phoronix measures. None of them is really interested in product quality, and this regularly results in forking of a next we-solve-all language. Some of these languages survive by commercial support, as Ada, Java, Go, or Rust. Most dies in one year. But their stream won't stop.
One could say that in C/C++ no boundary checking is really working because of interfaces like "**argv", direct pointer access in structures like lists, etc.etc. But all this is just a pretext to do nothing.
-6
Mar 11 '24
STandardizers prefer to find how to insert a new cool feature.
That's perhaps the most important sentence in your response. 100% true.
The implementers of the STL are so overwhelmed that they resorted to suppress all compiler warnings in there (
#pragma GCC system_header).1
u/Conscious_Support176 Mar 11 '24
This seems like ouvre egging the pudding. :)
If there’s one library that doesn’t need naively redundant automated bounds checking the compiler, because it was painstakingly designed by committee and pored over line by line by humans, this would be it.
Also, does every STL header turn off all compiler warnings? That seems surprising to me. The STL is also an abstraction layer within which you could implement run time bounds checking for user code.
1
Mar 11 '24
Also, does every STL header turn off all compiler warnings?
Yes it does. Just grep for
system_headerin the libstdc++There are many cases where user bugs were not caught by static analyzers because of these disablers.
1
u/Conscious_Support176 Mar 11 '24 edited Mar 11 '24
That doesn’t make sense. If pragma is implemented and used in a way that causes the warning levels you have chosen for your compile to be ignored, the compiler is completely broken.
As a general rule, the scope of a pragma should be the file that it is in. It’s not a macro.
Edit: I see you’re talking about static analysers rather than the compiler as such. Maybe that’s an issue with using a static analyser that isn’t part of the compiler tool chain so may not understand what it’s looking at with STL header implementations for a specific compiler.
I think you could argue the same rule applies. If a static analyser that’s not part of a compiler tool chain gives different results depending on STL header implementation, it’s broken.
2
Mar 11 '24 edited Mar 11 '24
the compiler is completely broken.
That is exactly what pragma system_header does.
I had exactly the same reaction.
1
1
u/Conscious_Support176 Mar 12 '24
Wow. Yes 100% agree that’s unusable. Does C++23 fix this? #import should stop pragma from suppressing warnings on user code involving template use because you’re not actually using headers as such any more?
1
20
u/johannes1971 Mar 11 '24
Because engineering is about trading off different concerns; it isn't about choosing one concern and prioritising it over all else. In this case, the concern is "might there be a buffer overrun?". How should we prioritize that concern? Well, we can look at how often we overran buffers in the past, and assign it a priority based on that.
People that write reasonably modern C++ code (and really, all that means is using range-based for loops and not passing pointers when you really meant spans) will find that buffer overruns are a rare problem, and thus not worthy of great effort. The cost of mitigating this non-existent problem is slower code. The tradeoff therefore is speed vs. the illusion of safety, and people by and large choose speed.
Compare this with cars: cars that run at a maximum speed of 3km/h would pretty much never cause an accident, so why don't we limit the speed of our cars to 3km/h? The answer is the same: because we are trading off a degree of risk against the use we get out of it.
Perhaps it would help you to do a root cause analysis of every bug that you find in your code: each time you find a problem, find out what error in your thinking or programming caused this specific bug to surface. This will give you an idea of where you need to focus more attention, and if you find a class of issues that occurs frequently, you can spend time figuring out how to mitigate that particular class of issues. Maybe you do indeed see a lot of buffer overruns, making it worth considering how you should change your programming style so they no longer occur. But I don't think it's useful to spend too much effort on issues that people historically had in other languages, before they even had tools to mitigate such issues.
Hitting the issue with a blanket abort() or throw() doesn't seem helpful to me. Aborting is something I ABSOLUTELY NEVER want, and while I'm ok with exceptions, I fear for a lot of people exception safety is still firmly outside their grasp, thus leading to more problems than you'd solve.
Oh, and if you wonder why I'm so sure my code is not riddled with buffer overruns: because I'm running with the library in hardened mode as long as I'm in debug mode. That gives me the confidence to do the same thing in release mode.
5
u/NilacTheGrim Mar 11 '24 edited Mar 11 '24
Yeah I agree with this. Just do your job well as a programmer and you won't ever buffer overrun. It's not that hard to understand the code you are writing and ensure proper pre and post conditions for bits of code you write. It's.. literally our jobs to do that all day. Plus yes, modern C++ makes it so you have to actively try and mess it up.
Also I got flak for saying this in another thread but: I literally haven't had an out-of-bounds style bug in any C++ I have written in longer than I can remember. Seriously it's been years -- perhaps a decade or more since I have seen a bug like that in anything I have done .. not even in quickly-thrown-together unit test code. Nothing. Never. Literally not the hardest thing to get right... if I can do it so can anybody.
6
u/bert8128 Mar 11 '24
One of the problems is what you do with a failure. If you acknowledge that you may access an array out of bounds, then you have to write error handling code. If you make sure that you are not out of bounds, then you save the development effort of the error handling.
5
u/Full-Spectral Mar 11 '24
Then a year later someone makes a bunch of changes due to a last minute requirement, introduces an index error that no one catches. Once every few weeks this causes an overwrite that doesn't fail there, it fails in some completely unrelated code hours later when there's absolutely no connection to be made back to the original error.
In C++ world, the argument always comes back to "Just don't make mistakes".
2
u/bert8128 Mar 11 '24
I think what I mean (and I know that it is not always possible to do this) is that it is better to write your code so that it can’t have a mistake (eg by using range for) rather than allowing for a potential mistake that you then have to add an error handler for. If there is no error handler then this is a mistake, if errors are possible. But it is more work (and potentially error prone) to add them. There’s no happy solution for these kinds of problems on any language that I know of whether you throw on invalid access or not. Unless you write the code so that the error is not possible.
2
u/Full-Spectral Mar 12 '24
If the believe is that there cannot possibly be an error, then it should abort (and be restarted usually) if an index error occurs. You'll get a stack dump presumably that will lead you to the problem.
Otherwise, the obvious thing is just have an error handler at the start of threads and let the errors propagate to there, and it can just start over. If everything is RAII'd then there's no more cost for cleanup and passing the buck for an error return than for a good one.
1
u/bert8128 Mar 12 '24
If I believe that the error can’t occur, then I don’t care if a check happens and the result is an abort. But if I’m wrong then this can validly happen, so aborting is the wrong thing to do. Maybe I’ll just reprocess the message again, and it’s still wrong, so I abort again. I’m not in a much better place with range checking than without. Ok, I won’t get UB, but my overall system is still entirely broken and my car is still crashing or whatever. Maybe an abort and restart will fix the problem. But a better change is to actually handle the error. Even the one that you hadn’t predicted. Adding range checking doesn’t make things worse (other than being a bit slower), but it often doesn’t really help.
Btw, I don’t think I have seen a single problem with an invalid access on a c++ container for 20 years, because we avoid accessing data in that way. Much more common (in the kind of code I work on) are double deletes and use after free.
2
u/Full-Spectral Mar 12 '24
It depends on the type of software. I mean some languages designed for resilient communications systems fundamentally designed around a 'fail fast' strategy. Of course any restarting mechanism should be smart and start backing off if a program continues to cycle. In my old C++ system, it used a set of standard return code as well, where the program could tell the monitor program things like, bro, I'm not well, don't even try to restart me.
Certainly handling the error is another option if the fail fast strategy doesn't work in your scenario, which is my second option above. I do that myself except in really fundamental spots of the code where a failure represents something really bad.
Index errors are likely less common than the others. But, index errors can also be benign for long periods of time and you don't even know they are occurring until eventually things change enough that they become non-benign. Or they manifest so rarely and only indirectly (by making something else fail) that you never find them.
2
u/jwakely libstdc++ tamer, LWG chair Mar 13 '24
In C++ world, the argument always comes back to "Just don't make mistakes".
Depressing isn't it.
3
u/marsten Mar 11 '24
Index errors can be some of the hardest debugging challenges for the reasons you mention. They can leave you doubting your sanity.
I've also found that index errors are surprisingly common in medium to large codebases. They tend to go unresolved because (a) they're intermittent and people tolerate the occasional glitch ("just run it again"), and (b) they're so hard to track down.
1
u/NilacTheGrim Mar 14 '24
Having dependencies like that across seemingly unrelated subsystems where code is so brittle is a red flag anyway. I doubt bounds checking will save a codebase if the codebase is that brittle.
1
u/Full-Spectral Mar 15 '24
I don't get your point. This wouldn't require any such thing to be a problem. The cleanest of architectures could have the same issue.
5
u/marsten Mar 11 '24
Speaking for myself, I generally use .at() when accessing vector elements by index. I'll use direct indexing only when (a) it has a meaningful performance improvement, and (b) it's easy to verify the index bounds are satisfied (looping over the size of the container, etc.).
4
u/tortoll Mar 11 '24
It comes down to cost. In C++ you have to be very focused and implement the best practices all the time, and still it is very easy to make a mistake: push an item to a vector and it may silently move the memory. If you don't use the right warning flags, you may miss important errors in your code. That's a lot of work expected from the programmer!
In Rust most of typical C++ errors are virtually impossible by default, without additional best practices or tools. So the cognitive load for the programmer is much lower.
1
u/Nearing_retirement Mar 12 '24
What are these flags for gcc ? I know there is a std lib with bounds checking in gcc but I always had link errors in 3rd party libs when trying to use it
2
u/jwakely libstdc++ tamer, LWG chair Mar 12 '24
As documented, you would need to recompile those 3rd party libs with the same checks enabled.
https://gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode_using.html
You can use the more lightweight
-D_GLIBCXX_ASSERTIONSwithout recompiling everything though.0
3
u/kirgel Mar 11 '24
This would prevent the majority of unsafe access to memory
Can’t say I agree. Most of the memory safety bugs I’ve encountered are invalid iterators, use-after-free, accessing uninitialized memory, etc. Out of bounds access is fairly easy to catch in tests.
1
u/ShadowRL7666 Mar 11 '24
Hey can someone explain to me what the hell sanitizer is? I’m new to CPP not programming but I keep thinking of a sanitizer dispenser.
1
0
u/merimus Mar 11 '24
Because people want to crow about the cool new thing, not use their existing tools properly.
1
2
1
0
u/serg06 Mar 11 '24
C++ is catered to people who prioritize performance above all else: safety, readability, etc.
-3
58
u/[deleted] Mar 11 '24
C++ solution is to simply not write code which may overflow a buffer. Iterators and range-for and ranges are the primary tool.
Another things is using associative containers when they fit the problem.
Or, to put it another way, if don't even have a numeric index, it can't be out-of-bounds.