简体   繁体   中英

Why program throws runtime error while iterating over an emtpy vector in c++

vector <int> o;    //Empty vector
for(int i=0;i<=o.size()-1;i++) cout<<o[i]; 

got runtime error in the above

vector <int> o;  
for(auto j : o){
 cout<<j<<" ";
            } 

However this code runs fine if iterator is used instead

o.size() is required by the C++ standard to return an unsigned type. When that's zero, subtracting 1 yields std::numeric_limits<decltype(o.size())>::max() which means your loop runs past the bounds of the empty vector.

for(std::size_t i = 0; i < o.size(); ++i) is the obvious fix. The use of <= and -1 seems almost disingenuously contrived to me.

o.size() will return an unsigned value of 0. Subtracting one from it returns a very large positive number, essentially making an infinite loop. Eventually your out-of-bounds array accesses to o[i] will result in a crash.

You could use

for(int i = 0; i <= int(o.size() - 1); i++)

Or just use the more typical

for(int i = 0;i < o.size(); i++)

where you check for "less than", not "less or equal" to a number one less.

Since sizeof(size_t) is greater or equal than sizeof(int) (although this might be implementation dependent) and size_t is unsigned , the int ( 1 ) is converted to size_t .

Therefore, in the expression o.size() - 1 , the 1 is implicitly converted to size_t , and o.size() - 1 (which is equivalent to size_t(0 - 1) ) becomes equal to std::numeric_limits<size_t>::max() . Therefore, the for loop is entered and accessing your empty o at index 0 results in undefined behavior.

You should:

for (size_t idx = 0; idx < o.size(); ++idx) { /* ... */ }

If for some reason you need the index to be of type int , you can:

for (int idx = 0; idx < static_cast<int>(o.size()); ++idx) { /* ... */ }

or in your example (which is less common):

for (int idx = 0; idx <= static_cast<int>(o.size()) - 1; ++idx) { /* ... */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM