markruff icon

Zombie Iterator for C++ Vector

markruff | PRO | 01/07/16 01:18:22 PM UTC | 0 ⭐ | 419 👁️ | Never ⏰ | []
C++ |

1 KB

|

None

|

0 👍

/

0 👎

/* 
 * Zombie Iterator
 *
 * Vector going out of scope leaving zombie Iterator
 * Is this a dangling pointer?
 */
 
#include <vector>
#include <iostream>
 
int main() {
  // these are in the scope of main()
  std::vector<int>::iterator it;
  std::vector<int>::iterator end;
 
  if ( true ) {
    // now we are in the scope of this block, lets cause trouble
    // this vector only exists for this block... then it's gone
    std::vector<int> v;
 
    // fill the vector with 10 integers
    for ( int i = 10 ; i > 0 ; i-- ) {
      v.push_back(i);
    }
 
    // get our iterators (one at the beginning, the other at the end
    it = v.begin();
    end = v.end();
 
    std::cout << "iterator while vector alive: " << *it << '\n';    
  }
 
  // The vector (v) is now gone... the following would be a compile time error
  // v.pop_back();
 
  // But this is not a compile time error... 
  for ( ; it != end ; it++ ) {
    std::cout << "iterating over dead vector: " << *it << std::endl; // naughty
    *it = 0; // very naughty
  }
}

Comments