0

I have to find the time it takes to for binary search for numbers from 1 to 2 billion but i cant use the data types. long int or long long int or any other shows segmentation fault. Upto 999999 works fine but 9999991 gives segmentation fault. please help.

 void binSch2(long  int arr[], long int x, long int l, long int h)
 {

    if(l>h)
    {
        printf("not present");
        return;
    } 
    unsigned long  int mid=l+(h-l)/2;
    if(arr[mid]==x)
    {
        printf("found %ld at %ld", x, mid);
    }
    else if(x<arr[mid]) binSch2(arr, x, l, mid-1);
    else if(x>arr[mid]) binSch2(arr,x , mid+1, h);

 }

int main()
{

    long  int limit=2000000000;
    long  int arr2[limit];
    for(long  int i=0; i<limit; i++)
    {
        arr2[i]=i+1;
    }
    long  int N2=sizeof(arr2)/sizeof(arr2[0]);
    long  int x2=88888;
    long  int z=0;

    clock_t begin = clock();
    binSch2(arr2, x2, z, N2-1);
    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("\ntime : %lf ", (double)(end - begin) / CLOCKS_PER_SEC);

    return 0;
}
7
  • 1
    Are you compiling as C or C++? The answers will be quite different for the two languages. Commented Jan 10, 2020 at 19:18
  • 1
    @Dead Pool Calculate how much space your array occupies. And take into account that variable length arrays is not a standard C++ feature. Commented Jan 10, 2020 at 19:18
  • 2
    Upto 999999 works fine but 9999991 gives segmentation fault. Is this a typo? 999999 and 9999991 differ by 8999992. Commented Jan 10, 2020 at 19:19
  • 3
    long int limit=2000000000; long int arr2[limit]; -- This is not valid C++. Second, even if it were valid syntax, the stack memory has been blown to bits with this declaration. Commented Jan 10, 2020 at 19:28
  • 2
    Your code is not valid C++: long int arr2[limit]; --> C++ doesn't support variable length arrays. Commented Jan 10, 2020 at 19:29

1 Answer 1

1

Try allocating memory in heap for arr2 variable as follow- see this

long int *arr2 = new long int[limit];

limited stack size is assigned for each function maybe(4k or 4M(large) pagesize) and local variables goes on the stack. So if you do the calculation, there is not enough space on stack for arr2 and program return access violation once it reach the stack limit. Also, don't forget to free the allocated space. delete [] arr2;

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

1 Comment

Prefer a std::vector to newing an array where possible. vector looks after itself much better than a raw dynamic array. In general, Why should C++ programmers minimize use of 'new'?

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.