cruntimesegmentation-faultgcc6

My C Code is encountering sigsegv error


Im not getting any error on local machine but codechef and ideone are giving runtime errors i use ubuntu with gcc 6.3 if by any chance if you know how to track that down please let me know so that i can use it for my further works heres the code

#include<stdio.h>
int main()
{
    int n, m, i, x, j;
    int a[n], b1, b2, b[n], c[m];
    do
    {
        scanf("%d%d", &n, &m);
    } while (!((1 <= n && n <= 100000) && (1 <= m && m <= 100000)));
    for (i = 1; i <= n; i++)
    {
        do
        {
            scanf("%1d", &a[i]);
        } while (!(0 <= a[i] && a[i] <= 9));
    }
    for (i = 1; i <= m; i++)
    {
        do
        {
            scanf("%d", &x);
        } while (!(1 <= x && x <= n));
        b1 = 0;
        b2 = 0;
        for (j = 1; j < x; j++)
        {
            b[j] = a[x] - a[j];
            if (b[j] > 0)
                b1 = b1 + b[j];
            if (b[j] < 0)
                b2 = b2 + b[j];
        }
        c[i] = b1 - b2;
    }
    for (i = 1; i <= m; i++)
        printf("\n%d", c[i]);
    return 0;
}

Solution

  • The problem is you're trying to use time travel to make your code work. In the below snippet of code you're declaring arrays using values you read in later, which clearly isn't going to work.

    int a[n], b1, b2, b[n], c[m];
    do
    {
         scanf("%d%d", &n, &m);
    

    Instead, you should declare them as int * and dynamically allocate enough space for them.

    int *a, b1, b2, *b, *c;
    do
    {
         scanf("%d%d", &n, &m);
    } while (!((1 <= n && n <= 100000) && (1 <= m && m <= 100000)));
    
    a=malloc(sizeof(int)*n);
    b=malloc(sizeof(int)*n);
    c=malloc(sizeof(int)*m);
    

    You'll need to remember to free the memory allocated later though.

    You also need to remember that arrays in C start at index 0, not 1, so where you have loops like:

    for (i = 1; i <= n; i++)
        do
        {
            scanf("%1d", &a[i]);
        } while (!(0 <= a[i] && a[i] <= 9));
    }
    

    they should be

    for (i = 0; i < n; i++)
        do
        {
            scanf("%1d", &a[i]);
        } while (!(0 <= a[i] && a[i] <= 9));
    }
    

    because otherwise if i is equal to n it'll be beyond the size of a.