0

When I add this function in my program, I get this error: "Segmentation fault". I have found that it is probably connected with pointers.

This is my function:

void deBoor(double* D, double* t, double x, int k, int n, double* R){
   int i,j,l;
   double ret[3];
   double* P=(double*)malloc(n*sizeof(double));
   for(i=0; i<n; ++i) P[i]=D[i];
   j=k;
   while(x<t[j]) ++j;
   while(x>=t[j+1]) ++j;
   for(l=1; l<=k; ++l){
       for(i=j; i>=j-k+l; --i)
       {
          P[i]=(x-t[i])/(t[i+k+1-l]-t[i])*P[i]+(t[i+k+1-l]-x)/(t[i+k+1-l]-t[i])*P[i-1];
       }
   }
   R[0]=P[j];
   free(P);
}

And this is the call of the function:

deBoor (kontrolne_tocke, prosirena_particija, xx, k, duljina, R);
John Ledbetter
  • 13,557
  • 1
  • 61
  • 80
user3100193
  • 531
  • 4
  • 6
  • 16
  • 4
    I hardly dare ask, but: did you debug? – Thorsten Dittmar Jan 28 '14 at 13:48
  • Start up gdb or some other debugger and see where the fault is. Also create a [minimal example](http://stackoverflow.com/help/how-to-ask) if you're still stuck. – dtech Jan 28 '14 at 13:49
  • Yes, I did. No errors are shown, and when I execute it then part of my code just print results, and at the part of that function is written "Segmentation fault" – user3100193 Jan 28 '14 at 13:51
  • Then read up on how to debug, e.g. set breakpoints at various points in the code and see where the segmentation fault occurs (at what instruction) – dtech Jan 28 '14 at 13:53
  • You don't check your inputs at all. How do you know that R[1] or R[2] are valid? Note that the value of the parameter n is critical and other parameters must have been correctly allocated so that accesses to them are valid. I am left to believe that all this has been done in the caller code. And I don't believe it. – Daniel Daranas Jan 28 '14 at 13:55
  • Which line gives the seg fault? What are the values of `x`, `k` and `n` in the function. What's the unused variable `ret` doing in the code? Your pair of loops incrementing `j` look like a plausible source of trouble; you go incrementing `j` without caring (knowing?) how big the array is. – Jonathan Leffler Jan 28 '14 at 14:34

1 Answers1

6

The code is rather unsafe. Some issues, not only about the safety but some of these certainly can cause your crash:

  1. Input arguments should be const pointers, for clarity.
  2. The return value of malloc() is not checked, so if the allocation fails you're toast.
  3. Don't cast the return value of malloc() in C.
  4. Don't copy using a loop, use memcpy().
  5. There's no guarantee that j doesn't go out of bounds.
  6. The ret array is never used.
Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606