Advertisement
markruff

Zombie Iterator for C++ Vector

Jan 7th, 2016
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. /*
  2.  * Zombie Iterator
  3.  *
  4.  * Vector going out of scope leaving zombie Iterator
  5.  * Is this a dangling pointer?
  6.  */
  7.  
  8. #include <vector>
  9. #include <iostream>
  10.  
  11. int main() {
  12.   // these are in the scope of main()
  13.   std::vector<int>::iterator it;
  14.   std::vector<int>::iterator end;
  15.  
  16.   if ( true ) {
  17.     // now we are in the scope of this block, lets cause trouble
  18.     // this vector only exists for this block... then it's gone
  19.     std::vector<int> v;
  20.  
  21.     // fill the vector with 10 integers
  22.     for ( int i = 10 ; i > 0 ; i-- ) {
  23.       v.push_back(i);
  24.     }
  25.  
  26.     // get our iterators (one at the beginning, the other at the end
  27.     it = v.begin();
  28.     end = v.end();
  29.  
  30.     std::cout << "iterator while vector alive: " << *it << '\n';    
  31.   }
  32.  
  33.   // The vector (v) is now gone... the following would be a compile time error
  34.   // v.pop_back();
  35.  
  36.   // But this is not a compile time error...
  37.   for ( ; it != end ; it++ ) {
  38.     std::cout << "iterating over dead vector: " << *it << std::endl; // naughty
  39.     *it = 0; // very naughty
  40.   }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement