Search code examples
cpointerssegmentation-faultbsearch

bsearch() returns (nil), causes segmentation fault


The bserach() function should return NULL but instead, I get (nil) when it is unable to find the key in the given array. What's going wrong?

#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}    
int values[] = { 5, 20, 29, 32, 63 };    
int main ()
{
   int *item;
   int key = 10;

   /* using bsearch() to find value 32 in the array */
   item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
   if( item != NULL ) 
   {
      printf("Found item = %d\n", *item);
   }
   else 
   {
      printf("Item = %d could not be found\n", *item);
   }       
   return(0);
}

Solution

  • In your code, in else part

    if( item != NULL ) 
       {
          printf("Found item = %d\n", *item);
       }
       else 
       {
          printf("Item = %d could not be found\n", *item);
       }
    

    even if item is NULL, youre dereferencing it [*item]. Please refrain from doing so.

    To fix the issue keeping the informative output message intact, maybe you can use something

    printf(" Any item with related key value %d could not be found\n", key);
    

    when item is NULL.