3

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);
alk
  • 69,737
  • 10
  • 105
  • 255
Fabricio
  • 7,705
  • 9
  • 52
  • 87
  • 2
    What is value of `str` argument to `bsearch`? Can you post compilable example that produces the seg fault? – hmjd Feb 07 '12 at 22:36
  • I updated, sorry. But now i think i can see my mistake hehehe. I forgot to pass a structure, i'm passing a string instead. – Fabricio Feb 07 '12 at 22:38

3 Answers3

3

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.

FatalError
  • 52,695
  • 14
  • 99
  • 116
3

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*.

hmjd
  • 120,187
  • 20
  • 207
  • 252
2

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);
}
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249