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

前端 未结 8 964
遇见更好的自我
遇见更好的自我 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:00

    Since s.length() is unsigned type quantity, when you do s.length()-3, it becomes negative and negative values are stored as large positive values (due to unsigned conversion specifications) and the loop goes infinite and hence it crashes.

    To make it work, you must typecast the s.length() as :

    static_cast < int > (s.length())

提交回复
热议问题