title: Mysterious Segmentation Fault in C++ Code
body: <p>It's been a while since I've coded C++ and I'm having some issues with this code sample:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;sstream&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  string* data;
  int current = 0;
  
  void init(){
      data = new string[6];
      data[0] = "7 4 3";
      data[1] = "8 11 12 16 17 18 20";
      data[2] = "17 16 20 2 20 5 13";
      data[3] = "17 8 8 16 12 15 13";
      data[4] = "12 4 16 4 15 7 6";
      data[5] = "8 14 2 11 17 12 8";
  }
  
  string getNext() {
      if(current == 0){
          init();
      }
      return data[current++];
  }
  
  void populate(int* target, int n){
      target = new int[n];
      string line = getNext();
      stringstream ss(line);
      for(int i=0; i&lt;n; i++){
          ss &gt;&gt; target[i];
          cout &lt;&lt; target[i] &lt;&lt; endl;
      }
      // THIS WORKS FINE
      for(int i=0; i&lt;n; i++){
          cout &lt;&lt; "TARGET" &lt;&lt; target[i] &lt;&lt; endl;
      }
  }
  
  int main() {
      string line;
      int n, s, e;
      int* x, * a, * b, * c, *d;
  
      line = getNext();
      stringstream ss(line);
      ss &gt;&gt; n &gt;&gt; s &gt;&gt; e;
      cout &lt;&lt; "N: " &lt;&lt; n &lt;&lt; " S: " &lt;&lt; s &lt;&lt; " E: " &lt;&lt; e &lt;&lt; endl;
  
      populate(x, n);
  
      // IMMEDIATE SEGMENTATION FAULT ON FIRST ITERATION
      for (int i = 0; i &lt; n; i++) 
          cout &lt;&lt; x[i] &lt;&lt; endl;
      populate(a, n);
      populate(b, n);
      populate(c, n);
      populate(d, n);
  
      return 0;
  }
  </code></pre>
  
  <p>In this program's final form, it will take user input, but for now I'm simulating input with an array of strings that I can read like I would read from cin.</p>
  
  <p>I have several pointers for integer arrays that I'm going to dynamically allocate and fill in each with one line of string input.</p>
  
  <p>I wrote the function <code>populate()</code> to do this for me so that I don't have too much duplicated code.</p>
  
  <p><code>populate()</code> seems to load the data fine into the specified pointer. I can even print it back out before returning from the function.</p>
  
  <p>HOWEVER, if I try to read the pointer AFTER <code>populate()</code> returns, I get an immediate segmentation fault. Any idea why? Is the reference being lost once the function returns? Do I have to convert the string chunks to ints explicitly in some manner? I'm a bit baffled by this.</p>
  
  <p><strong>GOT IT: been a while. Thank you!</strong></p>