This program is doing binary search in an int array (Kseek) using limits (low,up). Please ignore some instructions that seem to be weird, I have not finished all that must be done.
The strange thing is that my code runs perfectly in my university grader but segfaults for large test cases in my pc. I cannot understand where the mistake is, for inputs that have N>4000 elements it crashes.
I do not use any pointers or any memory allocation, I thought that scanf might segfault and tried to change some attributes but it still crashes.
Is it possible that gcc has "memory allocation boundaries" during compilation, and then when I am trying to run the program it cannot allocate the size of memory that I need??
If you have time to check my code please do, there might be a mistake that I cannot spot.
Thanks in advance!
#include <stdio.h>
int main()
{
int N, K, up, low, pos, flag=1 ;
scanf("%d %d\n", &N, &K);
int s[N], f[N], i=0;
while( scanf("%d %d\n", &s[i], &f[i]) != EOF) { i++; }
i=0;
up=f[0];
low=s[0];
while(i < N )
{
if ( f[i] > up) up=f[i];
if ( s[i] < low) low=s[i];
i++;
}
int Kseek[up];
i=0;
while( flag )
{
pos = ( low + up ) / 2;
i=0;
Kseek[pos]=0;
while ( i < N)
{
if ( pos >= f[i] )
{
Kseek[pos]=f[i]-s[i]+1+Kseek[pos];
}
else if ( pos >= s[i] && pos <f[i])
{
Kseek[pos]=pos-s[i]+1+Kseek[pos];
}
i++;
}
if ( Kseek[pos] == K ) flag=0;
else if ( Kseek[pos] > K )
{
i=0;
Kseek[pos-1]=0;
while ( i < N)
{
if ( (pos-1) >= f[i] )
{
Kseek[pos-1]=f[i]-s[i]+1+Kseek[pos-1];
}
else if ( (pos-1) >= s[i] && (pos-1) <f[i])
{
Kseek[pos-1]=(pos-1)-s[i]+1+Kseek[pos-1];
}
i++;
}
if ( Kseek[pos] > K && Kseek[pos-1] < K) flag=0;
else if ( Kseek[pos-1] == K ) { pos-=1; flag=0; }
up = pos - 1;
}
else if ( Kseek[pos] < K)
{
i=0;
Kseek[pos+1]=0;
while ( i < N)
{
if ( (pos+1) >= f[i] )
{
Kseek[pos+1]=f[i]-s[i]+1+Kseek[pos+1];
}
else if ( (pos+1) >= s[i] && (pos+1) <f[i])
{
Kseek[pos+1]=(pos+1)-s[i]+1+Kseek[pos+1];
}
i++;
}
if ( (Kseek[pos+1] > K && Kseek[pos] < K) || Kseek[pos+1] == K) { flag=0; pos+=1; }
low = pos + 1;
}
}
printf("%d\n", pos);
return 0;
}
Input files look always like this. Entries vary from 10 to 50000:
200 50536
369 732
595 644
460 500
548 975
270 546
662 766
358 767
719 929
284 354
411 949
169 210
488 679
103 462
180 188
364 487
407 477
234 586
23 775
504 698
79 906
......
...
First row is always K and N and next are s[i], f[i] for the next N lines.