0

This code has no problem without QueryPerformanceFrequency(&frequency); and QueryPerformanceCounter(&start); functions. Also when I use this functions with a sequential search program it works too. I could not figure out what is the problem here. Why I get segmentation fault?

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main()
{
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
double interval;

int i, c, first, last, middle, n, search, array[20000];

FILE *fptr;

//read sorted list file!
if((fptr = fopen("sorted.txt","r"))==NULL){
printf("Error in reading file !\n");
return 0;
}
//array of sorted list!
while(!feof(fptr)){
if(!feof(fptr)){
fscanf(fptr,"%d",&array[i]);
i++;}

}


printf("Enter value to find\n");
scanf("%d",&search);


first = 0;
last = 20000 - 1;
middle = (first+last)/2;

QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);

while( first <= last )
{
  if ( array[middle] < search )
     first = middle + 1;    
  else if ( array[middle] == search ) 
  {
     printf("%d found at location %d.\n", search, middle+1);
     break;
  }
  else
     last = middle - 1;

  middle = (first + last)/2;
}
if ( first > last )
  printf("Not found! %d is not present in the list.\n", search);

  QueryPerformanceCounter(&end);
interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;

printf("%f\n", interval);

system("pause");

return 0;   
}
6
  • And an evil #define LARGE_INTEGER char and your code's broken :P Commented Mar 30, 2013 at 17:16
  • Have you used a debugger and tried to narrow down the problem? Commented Mar 30, 2013 at 17:16
  • Just a side note here - you should be setting last = i - 1, not 20000 - 1. This assumes of course that i < 20000. If you use 20000, you are searching on invalid items. Commented Mar 30, 2013 at 17:16
  • 1
    while(!feof(ptr)) if(!feof(ptr)) Commented Mar 30, 2013 at 17:20
  • Another side note - binary searches require sorted arrays. From your code comments, your array is unsorted. Commented Mar 30, 2013 at 17:25

1 Answer 1

4

As far as I can tell, you are never defining i to something yet have a i++. At least that is the error I get when I try this code.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 That's a good point. it's been so long since I've done C. I forget about those uninitialized variables...
That was a really good point. When I initialized it, worked. You have been a big help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.