title: Use of setstate(3) doesn't produce expected sequence of random numbers
body: <p>For a multiplayer game I need to produce the same sequence of random numbers on all participating devices. Obviously, this is achieved by using the same seed on all devices. Problems arise when <code>random()</code> is called outside of the routine that is supposed to produce the same sequence on all devices. In this routine, I therefore try to use <code>setstate</code> to preserve the state array. As far as I understood <code>man random(3)</code>, calls to <code>random()</code> outside of this routine then should not change the sequence.</p>
  
  <p>However, the following code does not produce the same output for Run 1 and 2:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int main(int argc, const char * argv[])
  {
  
      char state[256];
  
      printf("Run 1 : ");
      initstate(123, state, 256);
      for (int i=1; i &lt; 10; i++) {
          printf("%ld ", random());
      }
  
      printf("\nRun 2 : ");
      initstate(123, state, 256);
      for (int i=1; i &lt; 10; i++) {
                  setstate(state); // load preserved state
                  printf("%ld ", random());
                  *state = *setstate(state); // preserve state 
                  random(); // this simulates a call to random() from outside
          }
          printf("\n");
          return 0;
  }
  
  
  Run 1 : 1597493280 1407130876 1753502901 1965067074 377602131 83146350 274392949 1718024305 1016176754 
  Run 2 : 1597493280 537479855 1611694138 941096776 83164437 1459338036 1256894804 1618690717 1091902527 
  Program ended with exit code: 0
  </code></pre>
  
  <p>Does anyone have any idea why?
  Or maybe there is another way to achieve the desired result?</p>
  
  <p>For the record: Running on OS X and iOS using Xcode 5.</p>
  
  <p><strong>EDIT</strong>
  With the help of Arkku and minitech, the following change makes Run 2's output identical to Run 1:</p>
  
  <pre><code>    printf("\nRun 2 : ");
  char otherstate[256];
  initstate(123, state, 256);
  for (int i=1; i &lt; 10; i++) {
      // preserve whatever state is currently active
      // and set the current state to "my" state
      memcpy(otherstate, setstate(state), 256);
      printf("%ld ", random());
      // switch back to the other state
      memcpy(state, setstate(otherstate), 256);
      // now this call does not affect the sequence that get's printf'd
      random();
  }
  printf("\n");
  </code></pre>