1

I think what I am doing in the code is legal, yet it shows runtime error. Why?

int main() {
    int q;
    cin>>q;
    while(q--)
    {
        int n, start;
        vector<int> adj[n];
        for (int i=0;i<n;i++)
        {
            for (int j=0;j<n;j++)
            {
                int x;
                cin>>x;
                //if(x==1) start = i;
                adj[i].push_back(x);
            }
        }

    }
    //code
    return 0;
}

Runtime Error: Runtime Error Abort signal from abort(3) (SIGABRT)

  • 4
    First, arrays must have a constant size in C++. Second, `n` is not initialized anywhere. – DeiDei Aug 06 '19 at 04:10
  • You make a variable `n` with no value, then try to create an array of that. Super undefined behaviour – Tas Aug 06 '19 at 04:10
  • Part of the reason is that [your code is ill-formed](https://stackoverflow.com/a/57367539/10957435). –  Aug 06 '19 at 04:13
  • 1
    You should use the highest warning level when you compile. gcc warning `warning: ‘n’ may be used uninitialized in this function [-Wmaybe-uninitialized]` – Paul Rooney Aug 06 '19 at 04:25

2 Answers2

2

This is not a valid c++ code:

vector<int> adj[n];

It may work on gcc and some other compilers, because of an extension they may have for c99 style array. If you turn on compiler warnings you can detect those. Live

As @Prakasht pointed out in their answer, there is also uninitialized variable n in the code. Using n is an undefined behavior anything can happen.

Oblivion
  • 7,176
  • 2
  • 14
  • 33
1

That's because you didn't initialise n. Just initialise n before declaring your vector. Something like n=10 or cin>>n.

prakasht
  • 448
  • 4
  • 16
  • 1
    While I agree that's part of the problem, it's not the only problem. –  Aug 06 '19 at 04:14
  • Correct! I used to code exactly like this in my starting days.:p – prakasht Aug 06 '19 at 04:15
  • Maybe I should have been more clear. Please see my comment on the original post. It will explain another major problem. –  Aug 06 '19 at 04:17
  • Thanks @Chipster. I also found a nice article [here](https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kills-The-VLA). Learning new things is great! – prakasht Aug 06 '19 at 04:25
  • @TamalMaity No. This question may help other people in the future. –  Aug 07 '19 at 04:46