Question

I have an array like this:

typedef struct INSTR
{
    char* str;
    int  argc;
} INSTR;
const static INSTR instructions[] = { {"blue",1}, {"green",2} };

then I tried to do a bsearch, but I'm getting Segmentation fault message:

int comp(const void *a, const void *b)
{
    const INSTR *aa = (INSTR*)a;
    const INSTR *bb = (INSTR*)b; 
    // if I "return 0;" here i get no error.
    return strcmp(aa->str, bb->str);
}

.

char *str = get_string(src_buff, size);
bsearch(str, instructions,
        sizeof(instructions) / sizeof(instructions[0]),
        sizeof(instructions[0]), comp);
Was it helpful?

Solution

The comp() function is incorrect.From here:

comparator Function that compares two elements. The function shall follow this prototype:

int comparator ( const void * pkey, const void * pelem );
The function must accept two parameters: the first one pointing to the
key object, and the second one to an element of the array, both
type-casted as void*. The function should cast the parameters back to
some data type and compare them.

The first argument to your comp() is a const char*, not a INSTR*.

Change to:

int comp(const void *a, const void *b)
{
    const INSTR *bb = (INSTR*)b; 
    return strcmp((const char*)a, bb->str);
}

Or, change the key to be a INSTR* instead of const char*.

OTHER TIPS

You are passing a variable named str as your key, but in the comparison function you're treating it like an INSTR. If your key is a string, then a should actually be a pointer to it, and you should be using

return strcmp(a, bb->str);

That's based on the assumption that str is in fact a string, but we can't bu sure without seeing it declared (I'm guessing it is unless you've got some rather unusual naming conventions).

EDIT:

Based on update it is a string.

The first argument to your comp function will be the argument that you passed as the first argument to bsearch, not a INSTR. Your comparison function should act accordingly:

int comp(const void *a, const void *b)
{
    const char* str = (const char*)a;
    const INSTR *bb = (INSTR*)b; 
    // if I "return 0;" here i get no error.
    return strcmp(str, bb->str);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top