Segmentation Fault Using bsearch in C

783 views Asked by At
player_t* getFirstMatch(player_t** sortedPlayers, int playerCount, char* inputString)
{
   player_t searchPlayer;
   player_t* searchPlayerPointer = &searchPlayer;

   searchPlayer.nameLast = inputString;

   searchPlayerPointer = (player_t*) bsearch(searchPlayerPointer, 
      *sortedPlayers, playerCount, sizeof(player_t*), 
      playerCompareLast);

   return searchPlayerPointer;
}

My program gets a segmentation fault on the line that uses bsearch(). What am I doing wrong here? Here is my comparison function. I was using a similar version for qsort, but now I need to use this one for bsearch :

int playerCompareLast(const void *p1, const void *p2)
{
  char* nameLast1;
  char* nameLast2;

  int result;

  nameLast1 = (*(player_t **)p1)->nameLast;
  nameLast2 = (*(player_t **)p2)->nameLast;

  result = strcmp(nameLast1, nameLast2);

  return result; 
}

The player_t type is just a Struct with a bunch of different members (like nameLast, nameFirst, etc.). I can't figure out what is wrong with my bsearch() arguments!

1

There are 1 answers

0
Remus Rusanu On

You are trying to use bsearch to search an array of pointers, apparently: the base argument is player_t** and the size argument is sizeof(player_t*). The implementation of playerCompare seems to match this, as it casts p to player_t**.

Alas, you are passing the key as player_t*, not as player_t**. To match the behavior of playerCompare your should pass &playerPointer (that is , player_t**).

I expect the access violation/seg fault to occur in playerCompare called by bsearch (including strcmp called from playerCompare), a quick inspection of the dump or a look in the debugger at the stack raising it should confirm.