0

The code is working perfectly fine with correct outputs in local cpp compiler and online cpp compiler, but i'm still getting a runtime error in codechef

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;

Kindly help

  • 2
    Could you use gdb to see where the error is happening? – gvl Jan 10 '20 at 20:54
  • 1
    `int arr[n][m];` is not standard C++. See https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – 463035818_is_not_an_ai Jan 10 '20 at 20:54
  • try more demanding test cases. Online coding contest dont reveal their test cases, but thats something we cannot help with. You first need to know what input makes the code crash before you can fix it – 463035818_is_not_an_ai Jan 10 '20 at 20:56
  • warning: ISO C++ forbids variable length array 'arr' [-Wvla] -> `int arr[n][m];` Compiled using gcc and -Wpedantic. It should point you into right direction; – Hawky Jan 10 '20 at 21:08
  • Note that `int arr[n][m];` can get very big very fast and can easily exhaust the available Automatic storage. This often results in a ... wait for it... Stack Overflow. `arr2` has the same problem. if `n` and `m` get up into the hundreds it could be game over. – user4581301 Jan 10 '20 at 21:08
  • Once you get past that, you'll probably get hammered on time. `arr` isn't used for anything other than taking input. Junk it. Read directly into `arr2` and save yourself an O(n*n) operation and a bucket-load of memory. – user4581301 Jan 10 '20 at 21:13
  • *The code is working perfectly fine with correct outputs in local cpp compiler and online cpp compiler, but i'm still getting a runtime error in codechef* -- There are only two issues with your code -- 1) The usage of those variable-length arrays. 2) Index out-of-bounds. Using `std::vector` fixes the first issue due to not using the stack memory, and using `std::vector::at()` instead of `[ ]` to access elements will diagnose the second issue. When you make those changes, then, as pointed out, you may get time-out errors (if not wrong answers), but not SIGSEGV's. – PaulMcKenzie Jan 10 '20 at 21:24

0 Answers0