title: Vector of pointers to dynamically-allocated objects: what could go wrong?
body: <p>I checked out this thread before posting here: <a href="https://stackoverflow.com/questions/1361139/c-vector-pointers-to-objects">How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++?</a></p>
  
  <p>Basically, I have some vectors of pointers that point to dynamically-allocated objects:</p>
  
  <pre><code>vector&lt;MyType*&gt; a;
  a.push_back(new MyType());
  </code></pre>
  
  <p>These vectors are private instance variables of a few classes I'm writing, and the dynamically-allocated objects are destroyed in the classes' destructors by iterating thru the vectors and calling <code>delete</code> on each pointer.</p>
  
  <p>It all works fine most of the time, but every once in a while a pointer in one of these vectors becomes invalid and causes a <code>segfault</code> when my code attempts to use it.  I'm having trouble figuring out why these pointers occasionally break.</p>
  
  <p>Are there any reasons why the dynamically-allocated object's address would change and cause the pointers to become invalid?</p>
  
  <p>I can try to post actual code if necessary.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Ok I have a number of things going on here.  There are two custom classes: <code>VisaLane</code> and <code>VisaResource</code>.  <code>VisaLane</code> contains a <code>vector&lt;VisaResource*&gt;</code> of pointers to VisaResources created using <code>new VisaResource()</code>.</p>
  
  <p>Each <code>VisaLane</code> is also created using <code>new VisaLane()</code> whose pointers are stored in a <code>vector&lt;VisaLane*&gt;</code>.</p>
  
  <p>This is one example of how the pointer gets corrupted.  Item 0 in the vector has inaccessible members:</p>
  
  <pre><code>resources_  &lt;3 items&gt;   std::vector&lt;VisaResource*&gt;
      [0]     VisaResource
          function_   &lt;not accessible&gt;    std::string
          name_   &lt;not accessible&gt;    std::string
          state_  VisaResource::FREE  VisaResource::VisaResourceState
          value_  6998928 uint
      [1]     VisaResource
          function_   "lane_clksel"   std::string
          name_   "m1_lane0_clksel"   std::string
          state_  VisaResource::FREE  VisaResource::VisaResourceState
          value_  0   uint
      [2]     VisaResource
          function_   "lane_bypass"   std::string
          name_   "m1_lane0_bypass"   std::string
          state_  VisaResource::FREE  VisaResource::VisaResourceState
          value_  0   uint
  visa_res_itr        __gnu_cxx::__normal_iterator&lt;VisaResource**, std::vector&lt;VisaResource*&gt;&gt;
  </code></pre>