Heatblast016 Heatblast016 - 3 months ago 17
C Question

C segmentation fault for no reason

I am taking edx's cs50 course and have run into a problem in my c code.
It gives me a segmentation fault for no obvious reason and all the other answers for this type of problem are too complicated for me to understand(I am a beginner)
It is a binary search function that will return true if it finds the value otherwise it will return false.
the code is as follows:

bool searchtruth(int vals[],int minimum, int maximum, int findval)
{
int min = minimum;
int max = maximum;
if(min - max == 1 && (findval < max &&findval > min))
{
return false;
}
int mid = min + ((min - max) / 2);
if(vals[mid] == findval)
{
return true;
}
else if(vals[mid] < findval)
{
return searchtruth(vals, mid , max, findval);
}
else if(vals[mid] > findval)
{
return searchtruth(vals, min , mid , findval);
}
else
{
return false;
}

}

Answer

There are two places in the code where you use

min - max

and in both places it should be

max - min