scottdraves / flam3

the original fractal flame renderer and genetic language
GNU General Public License v3.0
394 stars 73 forks source link

Possible bug in flam3_interpolate() when using smooth interpolation #13

Open mfeemster opened 8 years ago

mfeemster commented 8 years ago

This code in flam3_interpolate() appears to be buggy for two reasons:

       if (0 == i1) {
          fprintf(stderr, "error: cannot use smooth interpolation on first segment.\n");
          fprintf(stderr, "reverting to linear interpolation.\n");
          flam3_align(&cpi[0], &cps[i1], 2);
          smoothflag = 0;
       }

       if (ncps-1 == i2) {
          fprintf(stderr, "error: cannot use smooth interpolation on last segment.\n");
          fprintf(stderr, "reverting to linear interpolation.\n");
          flam3_align(&cpi[0], &cps[i1], 2);
          smoothflag = 0;
       }

       flam3_align(&cpi[0], &cps[i1-1], 4);
       smoothflag = 1;

If the code preceding the block shown has set i1 to 0, then it will call flam3_align() twice. Once in the first conditional, and again at the end. This could cause a crash on the second call because:

cps[i1-1]

Will be using an index of -1.

Worse, if ncps is 2 then this will call flam3_align() three times because the second block will be true, and then crash.

This will be the case when flam3_interpolate() is called from sheep_edge() since the spun array passed to it has two elements, and from flam3_cross() since the parents array also has two elements.

I believe the fix is to do the following:

if (0 == i1) 
{
          //...
}
else if (ncps-1 == i2)
{
         //...
}
else
{
       //...
}