SIGSEGV error

why am i getting a runtime error even when the code is working absolutely fine in gdb

int t,n,m,counter=0,x;
cin>>t;

for(int a=0;a<t;a++)
{
    cin>>n>>m;
    int arr[n][m];
    x=n*m;
    int arr2[x];
    counter=0;

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cin>>arr[i][j];
        }
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            arr2[i * m + j] = arr[i][j];
        }
    }
    for(int i=0;i<x;i++)
    {
        for(int j=i+m;j<x;j=j+m)
        {
            if((arr2[i]==1)&&(arr2[j]==1))
            {
                counter=counter+1;
            }
        }
    }
    cout<<counter<<endl;
    }
return 0;

}

Refer to this Stack Overflow Post for better understanding of Segmentation Fault or SIGSEGV Error Signal.
I will summarise what are causes of Segmentation Fault, however there are various scenarios which can lead to this error but the most popular ones are as follows:

  • If you try to read/write from/to a memory location whose access is not given to your program.

  • If you try to de-reference an un-initialised or NULL pointers.

  • If you try to access an index of an array which is out of range, or in other words out of bound access of an array index.

  • If you have already freed the dynamically allocated memory and then trying to access it.

  • If you try to change the data stored at read-only memory location i.e. to change the value of const variables.

You can see that this error is basically caused when your program accesses the memory incorrectly or violates the memory access rules.

Thanks for reading.
Peace :v:

This is not doing what you think it is doing - add the line:

cout << "i: " << i << " j: " << j << " a[i][j]: " << a[i][j] << endl;

underneath it, run it with the sample testcase, and observe the output.

In terms of why this is crashing, rather than just giving the wrong result: Iā€™m guessing somewhere along the line, with the full set of testcases, one (but not both) of n and m are being (mis-)read as 0, making x 0, making any attempt to access any element of arr2 Undefined Behaviour.

Edit:

Or n and m could be being (mis-)read as the decimal representation of large binary numbers, making x very large and resulting in a stackoverflow.

2 Likes