简体   繁体   中英

Segmentation Fault in a simple program

I have to submit some c++ code to a judge system which provides feedback.

However, I'm getting a segfault for the "hard testcases".

It would be really nice if someone could have a quick look at my code to help me out.

(the first input will always be a positive int)

#include <iostream>
using namespace std;

int main()
{
    long long t;
    cin >> t;
    bool table[t][t];
    long long n = t;
    int sum = 0;
    long long s;
    while(t--)
    {
        cin >> table[t][t];
        if (!table[t][t])
        {
            sum++;
        }
    }
    for(t=0;t<n;t++)
    {
        for(s=t+1;s<n;s++)
        {
            table[t][s] = 
                    (table[t][s-1] && !table[s][s]) ||
                    (!table[t][s-1] && table[s][s]);
            if(!table[t][s])
            {
                    sum++;
            }
        }
    }
    cout << sum << endl;
    return 0;
}

I do not see any possibility indexes would go out of range so most probably "hard cases" have t big enough to overflow the stack, as you use non standard for C++ dynamic array. Allocate data for your array on heap using std::vector

vector<vector<bool>> table{ t, vector<bool>{ t } };

vector<vector<bool>> table( t, vector<bool>( t ) ); // if you do not have C++11 yet

If I give input t= 2 the value you are reading using std::cin would be table[2][2] which is invalid index hence raising segmentation fault. Max index in case of t=2 would be table[1][1] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM