Reputation: 2369
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.
Upvotes: 0
Views: 1294
Reputation: 183602
fread_unlocked
returns 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 of InpFile
. For example, if you declare max_ipos
at global scope, you might write:
size_t bytes_read = fread_unlocked(InpFile, 1, MAXX, stdin);
// check for errors
max_ipos = &InpFile[bytes_read];
and then input_int
will need to detect when ipos == max_ipos
and terminate before reading *ipos
.
Edited to add: Note that (at the suggestion of Jonathan Leffler) I've switched the order of the arguments 1
and MAXX
to fread_unlocked
. This is because you want to read objects of size 1
, not objects of size MAXX
.
Incidentally, this:
inline int input_int(int flag=0)
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.)
Upvotes: 3
Reputation: 2885
Your code is very dirty code and everyone one to read it, be sure , will be confuse, So , i clean your code :
#include <stdio.h>
#include <iostream>
using namespace std;
int MAXX = 10000000;
char x = 0 ;
char *ipos = &x, InpFile[10000000];
inline int input_int(int flag=0){
while( *::ipos <= 32 )
++::ipos;
if(flag)
return(*::ipos++) -'0';
char 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;
}
By the way, You didn't mention to job of your program. Another your problem: you didn't initialize your ipos pointer.If you want to working with pointers, don't forget to initialize them.
Upvotes: 0