2007-02-11

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.

No comments:

Post a Comment