Unable to resolve the SIGSEGV Runtime Error

Hey Guys,
I am working on the problem LEBOMBS (http://www.codechef.com/problems/LEBOMBS).

I don’t know why I am getting a SIGSEGV.
My code is:


#include<stdio.h>
#include<string.h>
char arr[1005];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        int i,ans,ch;
        /* inputing the elements*/
        fflush(stdin);
        for(i=0; i< n;i++)
        {
            arr[i] = getchar();
        }
        fflush(stdin);
        n = strlen(arr);
        /*handling the case when no. of elements are 1*/
        if(n==1)
        {
            if(arr[0]=='1')
                printf("0\n");
            else
                printf("1\n");
            continue;
        }
        /*handling the 1st element separately*/
        /* 1=> bomb, 2=>the building was burnt, 0=>building was not burnt*/
        if(arr[0]=='1' && arr[1]=='0')
            arr[1] = '2';
        /*handling the rest of elements*/
        for(i=1;i < n-1;i++)
        {
            if(arr[i]=='1'){
                arr[i-1] = '1';
                if(arr[i+1]=='0')
                    arr[i+1] = '2';
            }
        }
        /*handling the last element */
        if(arr[n-1]=='1' && arr[n-2]=='0')
            arr[n-2] = '2';
        ans = 0;
        /*calculating the number of unburnt buildings*/
        for(i=0; i < n;i++)
        {
            if(arr[i]=='0')
                ans++;
        }
        printf("%d\n",ans);
    }
    return 0;
}

When I am using scanf instead of getchar() my code gives AC. What might be the problem.

The problem which I think is that you are changing the value of the variable n which you are taking as the input. You are using the same global array for all inputs. Hence strlen won’t work. As ‘\0’ is the terminator in scanf for the string but for getchar you need to put that character at the end of the string to make it work. Hence it would give you error. I haven’t checked the submission but try it.
You may also have to check the error with getchar() which sometimes takes ‘\n’ of the previous input.

1 Like