title: Why do I get a segmentation fault when using pthread_join?
body: <p>Here is the code I have, it compiles and runs using g++ but I get a segmentation fault. I know it happens around the pthread_join statement but I cant figure out why.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdio.h&gt;
  #include &lt;fstream&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sstream&gt;
  
  using namespace std;
  
  struct data{
      string filename;
      int x;
      int y;
  };
  
  void *threadFunction(void *input){
      data *file = (data *) input;
      string filename = file-&gt;filename;
      ifstream myFile;
      int xCount = 0;
      int yCount = 0;
      myFile.open(filename.c_str());
      string line;
      while(myFile &gt;&gt; line){
          if(line == "X"){
              xCount++;
          }else if(line == "Y"){
              yCount++;
          }
      }
      file-&gt;x = xCount;
      file-&gt;y = yCount;
      return (void *) file;
  }
  
  int main(){
      pthread_t myThreads[20];
      data *myData = new data[20];
  
      for(int i = 0; i &lt; 20; i++){
          ostringstream names;
          names &lt;&lt; "/filepath/input" &lt;&lt; i+1 &lt;&lt; ".txt";
          myData[i].filename = names.str();
          myData[i].x = 0;
          myData[i].y = 0;
      }
      for(int i = 0; i &lt; 20; i++){
          int check = pthread_create(&amp;myThreads[i], NULL, threadFunction, (void *) &amp;myData[i]);
          if(check != 0){
              cout &lt;&lt; "Error Creating Thread\n";
              exit(-1);
          }
      }
  
  
  
      int xCount = 0;
      int yCount = 0;
  
      for(int i = 0; i &lt; 20; i++){
          data* returnedItem;
          pthread_join(myThreads[i], (void**) returnedItem);
          xCount += returnedItem-&gt;x;
          yCount += returnedItem-&gt;y;
      }
  
      cout &lt;&lt; "Total X: " &lt;&lt; xCount &lt;&lt; "\n";
      cout &lt;&lt; "Total Y: " &lt;&lt; yCount &lt;&lt; "\n";
  
  }
  </code></pre>
  
  <p>Am I not calling return properly from my threadFunction? I've been trying a bunch of different things and I still don't know what's going on...any help would be greatly appreciated! (the text file I open contain either an X or Y per line. My goal is to count the total number of Xs and Ys in 20 text files)</p>