1

I have been working on find.c for the last three days, without success. When I run check50, 50% of the time it compiles helpers.c but then does not find 42 as it is supposed to. The other 50% of the time, it does not even compile helpers.c. If I try running find, it stops saying segmentation fault (core dumped). Could you PLEASE help?

1

As mentioned a number of times on SE and SO, Segmentation fault occurs due to accessing a memory location that stores nothing.

Here, you have applied a mixed concept of linear and binary search. You first divide the given array in two halves and then search for the required element in only one half(as per the condition).

The working code of search function(of yours) should be this

bool search(int needle, int haystack[], int size)
{ 
int i;
int half = size/2;
//for ( half=0;half>1;half=int(size/2))
//{  
     if (needle==haystack[half])
         return 1;
     else if (needle<haystack[half])
     {
         for (int i=half-1; i>0; i--)
         {
             if (haystack[i]==needle)
             return 1;
         }  
     }
     else if (needle>haystack[half])
     {
         for (int i=half+1; i<=size; i++)
         {
             if (haystack[i]==needle)
             return 1;
         }       
     }    
return 0; 
}

You didn't need to engage a loop (which I have commented) for this purpose. You did not assign a value to the variable half and that could be the reason for segmentation fault. Now the above code should work.

Better than trying to use a mixed form of search, you should try implementing both Linear Search and Binary Search individually.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .