title: caught segfault in [R] function
body: <p>I am very new to C but know my way around [R].  This error could be a very stupid mistake in C.   </p>
  
  <p>My C code does kernel smoothing.  </p>
  
  <p>*<em>When I comment out the last line of code my function works:  results[i] = v; *</em></p>
  
  <p>This call kills R:</p>
  
  <blockquote>
    <p>new.y&lt;-zsmooth2( x=c(0:80000), xpts=dat$V2, ypts=dat$V4, h=10000)</p>
  </blockquote>
  
  <p><strong>* caught segfault *</strong>
  address 0x1184f8000, cause 'memory not mapped'</p>
  
  <p>Traceback:
   1: .C("kernel_smooth", as.double(x), as.double(ypts), as.double(xpts),     as.integer(n), as.integer(nxpts), as.double(h), result = double(length(xpts)))
   2: zsmooth2(x = c(0:80000), xpts = dat$V2, ypts = dat$V4, h = 10000)</p>
  
  <p><strong>C-code:</strong>
  </p>
  
  <pre><code>#include &lt;R.h&gt;
  #include &lt;Rmath.h&gt;
  #include &lt;stdio.h&gt;
  
  
  void kernel_smooth(double *x, double *ypts,  double *xpts, int *n, int *nxpts, double *h, double *results){
      int i, j;
  
      for(i = 0; i &lt; *n; i++){
  
          double nsum = 0;
          double dsum = 0;
  
          double z = x[i] + *h;
          double y = x[i] - *h;
  
          for(j = 0; j &lt; *nxpts; j++){
  
              if(xpts[j] &lt; y){
                  continue;
              }   
              if(xpts[j] &gt; z){
                  break;
              }   
              double d = (xpts[j] - i) / *h;
              double r = dnorm(d, 0, 1, 0);
              nsum += r * ypts[j];
              dsum += r;  
          }   
              Rprintf("test:i %d\n", i);  
              double v = nsum / dsum;
              Rprintf("test:v %f\n", v);  
  
           results[i] = v;  
      }
  
  }
  </code></pre>
  
  <p><strong>R-code:</strong>
  </p>
  
  <pre><code> dyn.load("~/github/ZevRTricks/smoother1.so")
   zsmooth2&lt;-function(x, ypts, xpts, h){
      n &lt;- length(x)
      nxpts &lt;- length(xpts)
      dens  &lt;- .C("kernel_smooth", as.double(x), as.double(ypts), 
                  as.double(xpts), as.integer(n), as.integer(nxpts), 
                  as.double(h), result = double(length(xpts)))
  dens[["result"]]
  }
  </code></pre>