-3

When I declare vector< vector< int>> a(n), memory is allocated in heap whereas when I declare it vector< int> a[n], it is allocated on stack. But why? Doesn't the second one mean the way- a[i] is a pointer to the i-th vector, as the vectors are dynamically allocated in heap and hence the whole allocation should be in heap. Isn't it?

Could you please explain me if I am wrong?

2 Answers2

4
vector<int> adj[n];

This is not legal C++ code, you are not allowed to declare a dynamicaly sized array on the stack like this.

It's also probably the cause of your issue, as making such a huge allocation on the stack can cause some major issues.

You should use the following instead:

vector<vector<int>> adj(n);
  • This doesn't answer the question. While the statement is true, it is obviously an extension supported by his compiler, and is not really the cause of his problem. – Martin Bonner supports Monica Sep 07 '17 at 18:26
  • Yeah, it's legal for some compilers. Although I've never run across one, myself. – zzxyz Sep 07 '17 at 18:26
  • 3
    @zzyz some compilers letting you do it does not make it legal C++. Otherwise the same could be said of any undefined behavior, or strict aliasing violation. –  Sep 07 '17 at 18:27
  • 1
    @MartinBonner Added the explanation as to why I believe it's the root of the issue OP is trying to solve. Thanks! –  Sep 07 '17 at 18:29
  • @Frank Fair enough, and upvoted your answer based on your edit. – zzxyz Sep 07 '17 at 18:32
  • Actually it should be `vector> adj(n, {1} );` which would even eliminate next loop – Slava Sep 07 '17 at 18:40
0

As mentioned,

vector<int> adj[n];

is not standard C++, however some compilers (GCC) allow it as extension.

However such array is then created on the stack, and what you likely see is stack overflow (pun intended) - the stack is usually much smaller than the heap memory.

EmDroid
  • 5,918
  • 18
  • 18