I have a binarysearch function with interface as follows:
bool binarysearch(int* array, int size, int findnum) {
doBinarySearch(array, 0, (size-1), findnum);
}
The code for doBinarySearch is:
bool doBinarySearch(int* array, int start, int end, int findnum) {
if (end <= start)
return false;
int mid = (start+end)/2;
if (array[mid] == findnum) {
return true;
} else if (findnum < array[mid]) {
return doBinarySearch(array, start, mid, findnum);
} else {
return doBinarySearch(array, mid+1, end, findnum);
}
}
I wrote a unit test to test the above function. If I call binarysearch with empty array and wrong size from main, the code seg. faults as expected. E.g.
int main() {
int *array;
binarysearch(array, 10, -1);
}
But if I write a unit test class and have a function which does the above, then the binary search does not crash. Any idea, why the different behavior:
class TestBinarySearch {
public:
void testEmptyArray() {
int *array;
binarysearch(array, 10, -1);
}
};
int main() {
TestBinarySearch testObj;
// below line does not cause seg fault. and -1 is found for some reason
testObj.testEmptyArray();
}
Another question - Is there any way to detect the seg. fault if somebody calls the function with wrong size? I see some examples of using signals to catch that, but after that except exiting the program, can anything else be done?