Hacker News new | ask | show | jobs
by chlorion 961 days ago
C++ containers such as std::vector and std::array have bounds checking at least, though I have not saw them used very much.

Bounds checking instantly eliminates buffer overflow related unsafety, but not having it as the default is not good.

2 comments

The trouble with bounds checking via generics/macros is that the compiler doesn't know how to optimize out the checks. Most bounds checks can be optimized out of inner loops, where it really matters. But if the overflow test is just ordinary code, the compiler can't do that.

You also want to hoist bounds checks and do them early. Often, one check at loop entry can eliminate the bounds checks for each iteration. But the language has to allow an early fail.

They have bound checking through the `vec.at(index)` method, not through the indexing operator `vec[index]`. Most people won't even look at the `at` method, they will just use the indexing operator since that's supposed to be the "default" .
While true, most compilers do enable bounds checking in debug releases, and there are compiler flags to keep those checks enabled in release builds.
This is differently bad because it may mean tight loops are enormously slower under debug for no good reason, it's an adverse consequence of the C++ "wrong defaults" problem. Because they're defaults, we can't detect whether they're what was specifically needed or just nobody cared, so we guess nobody cared and act accordingly.
It isn't as if Rust is any different in this regard.
I'd argue exactly the contrary. In Rust you went out of your way to write the unsafe thing because that's specifically what you intended. As a result there's no need to try to guess whether this code doesn't care, if it didn't care it would be checked because that's the default.