SIGSEGV error with getchar and not with scanf

Hello all

I have the following code, if I submit it to codechef with scanf function to read the inputs it works fine, if I submit it with the ReadFastInt16() function to read inputs I get a SIGSEGV error, I have used the ReadFastInt16() function in other codechef problems and it accept the solution but I don't know why is giving me segmentation fault now, could anyone help me?

Thanks in advance



#include <iostream>
#include <cstdio>
#include <math.h>
#include <vector>
#include <time.h>
#include <string.h>
#include <cstdlib>
#include <memory>

using namespace std;

#define getNumber getchar()

unsigned int T = 0, N = 0, i = 0, j = 0;
char buf[8] = {0};

static int ReadFastInt16()
{
unsigned int int16 = 0;
register char charNumber = getNumber;
do
{
int16 = (int16 << 3) + (int16 << 1) + charNumber - '0';
charNumber = getNumber;
}while ((charNumber >= '0') && (charNumber <= '9'));

return int16;
}

int main(int argc, char* argv[])
{
T = ReadFastInt16();
//scanf("%d", &T);

while(T--)
{
N = ReadFastInt16();
//scanf("%d", &N);
int A[N][N];

for (i=0;i<N;i++)
for (j=0;j<=i;j++)
A[i][j] = ReadFastInt16();
//scanf("%d", &A[i][j]);

for (i=N-1;i>0;i--)
for (j=0;j<i;j++)
A[i-1][j] += A[i][j] > A[i][j+1]?A[i][j]:A[i][j+1];

memset(&buf,0,sizeof(buf));
sprintf(buf,"%d\n",A[0][0]);
fwrite(buf, 1, strlen(buf), stdout);
//printf("%d\n",A[0][0]);
}
return 0;
}
ReadFastInt16 isn't nearly as robust as the scanf version (and will return some odd values if you begin with a non-digit in the input.) I doubt it would make much difference in most of the Code Chef problems as the format of input is usually pretty uniform, however any input where there were consecutive whitespace characters in the input stream will screw your function up. Have you tried changing it to something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cctype>

unsigned ReadFastInt16()
{
    char digit = getchar();

    while (std::isspace(digit))
        digit = getchar();

    unsigned n = 0;
    while (std::isdigit(digit))
    {
        n = n * 10 + digit - '0';
        digit = getchar();
    }

    return n;
}
Thanks a lot, I didn't try with consecutive whitespaces, that was the problem, I implemented the isspace and isdigit conditions and now its working
Topic archived. No new replies allowed.