Trap Following Code Vector Init Forint

11 Feb 2007 / Edit / History
a trap I met today

the following code:


vector<int> a;
// init a
for(int i = 0; i < a.size()-1; i+=2) {
// do something;
}


will crash if a is empty, because a.size() return a size_t, which is unsigned, then a.size()-1 is a very large unsigned value. it should be changed to:


vector<int> a;
// init a
for(int i = 0; i+1 < a.size(); i+=2) {
// do something;
}


P.S. I does not consider a.size() > 2G, at least it will not happen in this program.

Tags: c++

Related Posts:

comments powered by Disqus
Copyright © 2017 LI Daobing, Powered by github:pages, Jekyll, bootstrap, Designed by quanquan
Fork me on GitHub