title: R freezes when I call a C code
body: <p>I wrote a small C code to do random walk metropolis, which I call in R. When I run it, R freezes. I am not sure which part of the code is incorrect. I following this <a href="http://www.biostat.jhsph.edu/~rpeng/docs/interface.pdf" rel="nofollow">Peng and Leeuw tutorial</a> (on Page 6). As a disclaimer: I don't have much experience with C, and have only some basic knowledge of C++</p>
  
  <pre><code>#----C code --------
  #include &lt;R.h&gt;
  #include &lt;Rmath.h&gt;
  
  void mcmc(int *niter, double *mean, double *sd, double *lo_bound, 
            double *hi_bound, double *normal)
  {
      int i, j;
      double x, x1, h, p;
      x = runif(-5, 5);
      for(i=0; i &lt; *niter; i++) {
          x1 = runif(*lo_bound, *hi_bound);
          while((x1 + x) &gt; 5 || (x1 + x) &lt; -5)
              x1 = runif(*lo_bound, *hi_bound);
          h = dnorm(x+x1, *mean, *sd, 0)/dnorm(x, *mean, *sd, 0);
          if(h &gt;= 1)
              h = 1;
          p = runif(0, 1);
          if(p &lt; h)
              x += x1;
          normal[i] = x;
      }
  }
  
  
  #-----R code ---------
  foo_C&lt;-function(mean, sd, lo_bound, hi_bound, niter)
  {
      result &lt;- .C("mcmc",  as.integer(niter), as.double(mean), as.double(sd), 
                   as.double(lo_bound), as.double(hi_bound), normal=double(niter))
      result[["normal"]]
  }
  </code></pre>
  
  <p>After compiling it:</p>
  
  <pre><code>dyn.load("foo_C.so")
  foo_C(0, 1, -0.5, 0.5, 100)
  </code></pre>
  
  <p><strong>FOLLOW UP:</strong>
  The <code>while</code> loop is where the problem lies. But the root of the problem seems to have to do with the function <code>runif</code>, which is supposed to generate a random variable between a lower bound and an upper bound. But it seems that what the function actually does is to randomly pick either the upper bound value (5) or the lower bound value (-5).</p>