2 ms·
Here is my favorite example of errors due to overflow: std::vector<int> vec; // test for sorted.. bool sorted = true; for (size_t i = 0; i < vec.size() - 1U
by gregfjohnson 3y ago
Here is my favorite example of errors due to overflow:
std::vector<int> vec;
// test for sorted..
bool sorted = true;
for (size_t i = 0; i < vec.size() - 1ULL; ++i)
if (vec[i] > vec[i+1]) {
sorted = false;
break;
}
I believe the google c++ style guide rues the selection of unsigned integers as the return type of size() in the standard library for reasons like the above. Personally, my preferred behavior would be to have a compiler flag that could be used to enable a trap if unsigned arithmetic resulted in wrap-around, as in the above case when the vector is of length zero.
- planede 3y ago> Personally, my preferred behavior would be to have a compiler flag that could be used to enable a trap if unsigned arithmetic resulted in wrap-around, as in the above case when the vector is of length zero. That probably has the potential of having too many false positives. It's also very non-confroming, so I see why compiler vendors would be reluctant to add such a flag.
- jcelerier 3y ago> compiler flag that could be used to enable a trap if unsigned arithmetic resulted in wrap-around, as in the above case when the vector is of length zero. I mean.. this is exactly what -fsanitize=integer does in clang. I never saw a signed overflow UB, but how many "perfectly defined" yet horrendously wrong cases like this one this sanitizer has helped me find...
- gregfjohnson 3y agoThanks so much - I was unaware of this clang flag. I just confirmed, it does exactly what I was hoping for! I suggested that this be an optional flag, not the default behavior. I could see using it for unit-test/static-analysis builds where performance is not the main concern. (I have not looked at the generated assembly or done a performance comparison, but it might be that the -fsanitize=integer flag would slow the generated code down.)
- jcelerier 3y agoAnything that starts with -fsanitize is really only meant for debugging, definitely not production.