Friday, November 13, 2015

STL vector out-of-bound access is an undefined behavior


Found a bug today, which is a well-known pitfall in C++.

Consider the following code, std::vector::operator[] won't perform any boundary check on the index, a out-of-bound access is an undefined behavior.

#include <vector>                                                               
#include <iostream>                                                             
                                                                                
int main (void) {                                                               
  std::vector<bool> a(10);                                                      
                                                                                
  for (auto x : a)                                                              
      x = true;                                                                 
                                                                                
  if (a[11] == false)                                                           
      std::cout << "gg";                                                        
                                                                                
  return 0;                                                                     
}


gg

----

On the other hand, std::vector::at will yield an exception on out-of-bound access.


#include <vector>                                                               
#include <iostream>                                                             
 
int main (void) {                                                               
  std::vector<bool> a(10);                                                      
 
  for (auto x : a)                                                              
      x = true;                                                                 
 
  if (a.at(11) == false)                                                           
      std::cout << "gg";                                                        
 
  return 0;                                                                     
}


terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 11) >= this->size() (which is 10)

No comments:

Post a Comment