title: How memory is shared between threads in C
body: <p>I am trying to understand how memory is shared between threads.</p>
  
  <p>I know that every thread has his own stack while heap is shared between every threads. Every thread shares common addressing space, so a local variable inside a thread can be seen by another thread using pointers. This is done by using POSIX library pthread, in Linux.</p>
  
  <p>So, assumming that it is right, if I create a thread with a local var allocated in his stack, another thread should read a wrong value if the stack frame containing var is destroyed. With this code, it works in this way.</p>
  
  <pre><code>void *_th2(void *args) {
  
      sleep(1);
      printf("0x%x\n", *(int *)args);
      fflush(stdout);
  
      pthread_exit(NULL);
  }
  
  void *_th1(void *args) {
      pthread_t tid;
      int var = 10;
  
      pthread_create(&amp;tid, NULL, _th2, (void *)&amp;var);
      pthread_exit(NULL);
  }
  </code></pre>
  
  <p>But if I create var with a malloc to allocate it in the heap, it doesn't show right value. Why? The code is below</p>
  
  <pre><code>void *_th2(void *args) {
  
      sleep(1);
      printf("0x%x\n", *(int *)args);
      fflush(stdout);
  
      pthread_exit(NULL);
  }
  
  void *_th1(void *args) {
      pthread_t tid;
      int *var = malloc(sizeof *var);
  
      *var = 10;
      pthread_create(&amp;tid, NULL, _th2, (void *)var);
      pthread_exit(NULL);
  }
  </code></pre>