title: EXC_BAD_ACCESS only when building object inside function
body: <p>I'm working on a C++ project in XCode and I'm getting what appears to be some strange behavior (based on how I understand it). Here's my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;string&gt;
  
  class beep {
  public:
      virtual void greet() {
          std::cout &lt;&lt; "bleep\n";
      }
  };
  
  class boop : public beep {
  public:
      void greet() {
          std::cout &lt;&lt; "bloop\n";
      }
  };
  
  class beep_master {
  public:
      std::vector&lt;beep*&gt; beeps;
  
      void beep_everything() {
          for (int i = 0; i &lt; beeps.size(); i++) {
              beeps[i]-&gt;greet();
          }
      }
  };
  
  beep_master factory() {
      boop boop1;
      boop boop2;
  
      beep_master master;
      master.beeps.push_back(&amp;boop1);
      master.beeps.push_back(&amp;boop2);
  
      return master;
  }
  
  int main(int argc, const char * argv[]) {
      beep_master master = factory();
  
      beep_master* ref = &amp;master;
  
      ref-&gt;beep_everything();
  
      return 0;
  }
  </code></pre>
  
  <p>I'm running this via XCode, and I'm getting an <code>EXC_BAD_ACCESS</code> in the <code>for</code>-loop in <code>beep_master</code>. Everywhere I've looked on the internet seems to indicate this is due to some memory management issues but I'm not really allocating anything dynamically.</p>
  
  <p>I've noticed that if I move the contents of <code>factory</code> into <code>main</code> that I no longer get the error which leads me to believe it has something to do with <code>boop1</code> and <code>boop2</code> going out of scope and making the pointers invalid after the code exits that function.</p>
  
  <p>Noodling on this, I'm beginning to think that this issue is unavoidable without the use of dynamic memory via the <code>new</code> operator and <code>shared_ptr</code>. Is this the right direction, or am I missing something in my setup here?</p>