Search code examples
c++visual-studiostack-overflow

Stack overflow for my code on Visual Studio


I have been writing solution to a problem on UVa Online Judge, and when testing my code on Visual Studio it gives the

Unhandled exception at 0x01228249 in Light raods.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00A02000).

message, which I do not understand, because I do not spot any error in the code itself. Here is my code:

#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
using namespace std;
#define MAX 1000000000
int m, n;
int main() {
    int aaa = 0;
    while (cin >> m >> n&&m != 0 && n != 0) {
        int totallength = 0;
        vector<pair<int, int>>neibs[200001];
        for (int i = 0; i < n; i++) {
            int x, y, z;
            cin >> x >> y >> z;
            neibs[x].push_back(make_pair(y, z));
            neibs[y].push_back(make_pair(x, z));
            totallength += z;
        }
        int totalmst = 0;
        int dist[200001];
        for (int i = 0; i <= m; i++) {
            dist[i] = MAX;
        }
        int treesize = 1;
        priority_queue<pair<int, int>>q;
        dist[0] = 0;
        bool intree[200001] = { 0 };
        intree[0] = 1;
        for (int i = 0; i < neibs[i].size(); i++) {
            int next = neibs[0][i].first;
            int val = neibs[0][i].second;
            dist[next] = val;
            q.push(make_pair(val, next));
        }
        while (treesize < m) {
            int minnode, mindis = MAX;
            minnode = q.top().second;
            mindis = q.top().first;
            intree[minnode] = true;
            totalmst += mindis;
            treesize++;
            for (int i = 0; i < neibs[minnode].size(); i++) {
                int next = neibs[minnode][i].first;
                int val = neibs[minnode][i].second;
                if (!intree[next] && dist[next] > val + dist[minnode]) {
                    dist[next] = val + dist[minnode];
                    q.push(make_pair(dist[next], next));
                }
            }
        }
        cout << totallength - totalmst << endl;
    }
    return 0;
}

Is there something wrong with my code or with my Visual Studio? Thanks for helping me.


Solution

  • You should allocate both the vectors you use in heap:

    std::unique_ptr<vector<pair<int, int>>> neibs(new vector<pair<int, int>>[200001]);
    
    std::unique_ptr<priority_queue<pair<int, int>>> q(new priority_queue<pair<int, int>>());