i am using a Unix machine and i am trying to read from console till EOF is reached (am supplying with Ctrl+D) . I am using fread_unlocked, For the input read, it outputs the read integers correclty but instead of a normal exit , it gives segmentation fault on EOF . How do i modify my code so that it behaves as expected?
int MAXX = 10000000;
char *ipos, InpFile[MAXX];
inline int input_int(int flag=0)
{
while(*ipos<=32)
++ipos;
if(flag)
return(*ipos++-'0');
LL x=0,neg=0;
char c;
while(true)
{
c=*ipos++;
if(c=='-')
neg=1;
else
{
if(c<=32)
return neg?-x:x;x=(x<<1)+(x<<3)+c-'0';
}
}
}
int main()
{
ipos = InpFile;
fread_unlocked(InpFile, MAXX, 1, stdin);
while(true){
int n = input_int();
printf("%d\n",n);
}
return 0;
}
My input from the console is : 3 4 5 6Ctrl+D
THe output i get now is : 3 4 5 6 Segmentation Error
Expected output: 3 4 5 6
Thanks.
fread_unlockedreturns the number of bytes that were actually read. You need to take that return value, and you need to make sure that you never try to use more than that many characters out ofInpFile. For example, if you declaremax_iposat global scope, you might write:and then
input_intwill need to detect whenipos == max_iposand terminate before reading*ipos.Edited to add: Note that (at the suggestion of Jonathan Leffler) I’ve switched the order of the arguments
1andMAXXtofread_unlocked. This is because you want to read objects of size1, not objects of sizeMAXX.Incidentally, this:
is not valid C. Default values for arguments are a C++ thing. (Maybe there are C compilers that support it as an extension — I don’t know — but there are definitely C compilers that don’t.)