title: Getting Segmentation Fault in C when using sleep with Pthreads
body: <p>I am creating a thread in C with PThreads which executes a function that is running in an infinit loop and prints some random json string every second into the console. At the beginning he prints the result of the function simulateLED with no problem, but after sleeping for 1 second, I'll get a Segmentation Fault (Core dumped). If I remove sleep, I'll not get it and the program works fine. Why do I get a Segmentation Fault with sleeping and how to fix it?</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  
  char *simulateLED() {
      int temp;
      int luftf;
      char* jsonString;
  
      time_t t;
      srand((unsigned) time(&amp;t));
  
      int x=-10, y=50;
      temp=(rand()%((y+1)-x))+x;
  
      x=2, y=30;
      luftf=(rand()%((y+1)-x))+x;
  
      printf("%d %d\n", temp, luftf);
      fflush(stdout);
  
      sprintf(jsonString, "{\n\"TEMP\": %d,\n\"HUMI\": %d\n}", temp, luftf);
  
      return jsonString;
  }
  void *simAndSendThread(void *param) {
      while(1) {
          printf("%s", simulateLED());
          sleep(1);
      }
  }
  int main(int argc, char *argv[]) {
      pthread_t thread;
  
      if(pthread_create(&amp;thread, NULL, simAndSendThread, NULL)) {
          fprintf(stderr, "Error creating thread\n");
          return 1;
      }
  
      if(pthread_join(thread, NULL)) {
          fprintf(stderr, "Error joining thread\n");
          return 2;
      }
  
      pthread_exit(NULL);
      return 0;
  }
  </code></pre>