user3100193
user3100193

Reputation: 561

Segmentation fault in c - probably connected with pointers

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);

Upvotes: 0

Views: 73

Answers (1)

unwind
unwind

Reputation: 399703

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.

Upvotes: 6

Related Questions