C++ crashes in a 'for' loop with a negative expression

前端 未结 8 910
遇见更好的自我
遇见更好的自我 2020-12-24 11:00

The following code crashes C++ with a runtime error:

#include 

using namespace std;

int main() {
    string s = \"aa\";
    for (int i = 0; i         


        
8条回答
  •  隐瞒了意图╮
    2020-12-24 11:12

    Actually, in the first version you loop for a very long time, as you compare i to an unsigned integer containing a very large number. The size of a string is (in effect) the same as size_t which is an unsigned integer. When you subtract the 3 from that value it underflows and goes on to be a big value.

    In the second version of the code, you assign this unsigned value to a signed variable, and so you get the correct value.

    And it's not actually the condition or the value that causes the crash, it's most likely that you index the string out of bounds, a case of undefined behavior.

提交回复
热议问题