title: Pthread_create causing segmentation fault in C++
body: <p>I'm trying to accept an Integer value, and create that number of threads in a program. Bizarre enough, only the first thread can be created. After some tracing, it shows that pthread_create is the line that causes core dump.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;time.h&gt;
  #include &lt;pthread.h&gt;
  using namespace std;
  
  class Kevin
  {
  public:
      Kevin();
      static void* Speak(void* value);
  };
  
  Kevin::Kevin()
  {
      cout &lt;&lt; "new instance of Kevin is created\n";
  }
  
  void* Kevin::Speak(void* value)
  {
      cout &lt;&lt; "Name: Kevin" &lt;&lt; *((int*)value) &lt;&lt; "\n" &lt;&lt; "Seconds since epoch:" &lt;&lt; "\nThread id:" &lt;&lt; pthread_self() &lt;&lt; endl;
  }
  
  int main(int argc, char *argv[])
  {
      int threadsNumb = atoi(argv[1]);
      cout &lt;&lt; "number of threads :" &lt;&lt; threadsNumb &lt;&lt;endl;
      int status;
      int i;
      pthread_t threads[threadsNumb];
      for(i=0;i&lt;threadsNumb;i++)
      {
          cout &lt;&lt; "what is i? " &lt;&lt; i &lt;&lt; endl;
          cout &lt;&lt; &amp;threads[i] &lt;&lt; i &lt;&lt; endl;
          cout &lt;&lt; "threads" &lt;&lt; threads[i] &lt;&lt; endl;
          cout &lt;&lt; "thread Numb" &lt;&lt; threadsNumb &lt;&lt; endl;
  
          pthread_create(&amp;(threads[i]),NULL,Kevin::Speak,(void *)&amp;i); // this line
          pthread_join(threads[i], (void **)&amp;status);
          cout &lt;&lt; endl;
      }
      return EXIT_SUCCESS;
  }
  </code></pre>
  
  <p>Running with "./a.out 3" gives the output of:</p>
  
  <pre><code>number of threads :3
  what is i? 0
  0x7fff3600ae400
  threads6296496
  thread Numb3
  Name: Kevin0
  Seconds since epoch:
  Thread id:1117690176
  
  what is i? 1
  0x7fff000000081
  Segmentation fault (core dumped)
  </code></pre>
  
  <p>I tried moving the declaration of <code>pthread_t threads[threadsNumb];</code> into the for loop, it can run but it will gives me all same Thread id, which is not desired. Any idea what might be the cause of core dump? It's taken me hours to resolve just this one minor issue.
  I've also looked into a similar question but I did not re-declare anything: <a href="https://stackoverflow.com/questions/11249588/pthread-create-causing-segmentation-fault">pthread_create causing segmentation fault</a></p>
  
  <p>This is what I get after changing the 2nd argument of pthread join to NULL.</p>
  
  <pre><code>what is i? 0
  0x7fffe23e12f00
  threads6296496
  thread Numb3
  Name: Kevin0
  Seconds since epoch:
  Thread id:1098664256
  
  what is i? 1
  0x7fffe23e12f81
  threads242525729787
  thread Numb3
  Name: Kevin1
  Seconds since epoch:
  Thread id:1098664256
  
  what is i? 2
  0x7fffe23e13002
  threads47489276644304
  thread Numb3
  Name: Kevin2
  Seconds since epoch:
  Thread id:1098664256
  </code></pre>
  
  <p>Why is the Thread id same?</p>