lfind is returning a segmentation fault when it cannot find an element in an array on OSX 10.8. I copied the code from Apple (lsearch.c) and found that the comparison (element < end) as part of the for loop in linear_base was returning true even when it should have returned false, so it just ran off the end of the array. Am I passing in wrong arguments? The example below returns:
Yes (For bsearch with the element present)
Yes (For lfind with the element present)
No (For bsearch with the element absent)
Segmentation fault (For lfind with the element present).
Thanks in advance for any help.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int CompareChar(const void *elemA, const void *elemB) {
return (*(char *)elemA - *(char *)elemB);
}
int main() {
void *alphabet = malloc(26 * sizeof(char));
int i;
for(i = 0; i < 26; i++) {
char ch = 'A' + i;
memcpy((char*) alphabet + i, &ch, sizeof(char));
}
char searchCh1 = 'N';
char searchCh2 = '9';
int nelem = 26;
bsearch((void*) &searchCh1, alphabet, nelem, sizeof(char), CompareChar) == NULL ? printf("No\n") : printf("Yes\n");
lfind((void*) &searchCh1, alphabet, &nelem, sizeof(char), CompareChar) == NULL ? printf("No\n") : printf("Yes\n");
bsearch((void*) &searchCh2, alphabet, nelem, sizeof(char), CompareChar) == NULL ? printf("No\n") : printf("Yes\n");
lfind((void*) &searchCh2, alphabet, &nelem, sizeof(char), CompareChar) == NULL ? printf("No\n") : printf("Yes\n");
return 0;
}