繁体   English   中英

具有相同数组索引的C ++分段错误

[英]C++ Segmentation fault with same array index

我有以下代码:

bool *pho=new bool[n];
memset(pho, 0, sizeof(bool) * n);

for (int i = 0; i < m; i++) {
    int d=2;

    cout << "i=" << i << ", d="<<d<< endl;

    pho[d] = true;
}

使用输入n=8运行将产生以下输出:

i=0, d=2
i=1, d=2
[Segfault]

我不明白为什么会这样! 由于某种原因,在阵列中设置相同的位置会导致段错误。 我已经多次运行该程序,它始终会产生相同的输出。

使用调试器逐步执行代码,可以看到访问数组时d的值(索引)为2。

我尝试使用全局数组以及静态全局数组,这两种方法都会导致相同的错误。

我的IDE和编译器有问题吗? 我将MinGW与Eclipse CDT结合使用,并启用了std / c ++ 11选项。

这是整个源文件,以防程序的任何其他部分引起问题:

#include <iostream>
#include <queue>
#include <vector>
#include <unordered_set>
#include <utility>
#include <algorithm>
#include <cstring>

using namespace std;

vector<unordered_set<int>> adj;

static bool *visited;

pair<int, int> dfs(int node) {
    if (visited[node])
        return make_pair(0, node);
    pair<int, int> best = make_pair(0, node);
    for (int neigh : adj[node]) {
        pair<int, int> alt = dfs(node);
        alt.second++;
        best = max(best, alt);
    }
    return best;
}

int main(int argc, char** argv) {
    int n, m, def;
    cin >> n ;

    cin >> m;

    bool *pho=new bool[n];
    memset(pho, 0, sizeof(bool) * n);


    int *degrees=new int[n];
    memset(degrees, 0, sizeof(int) * n);

    cout << "n="<<n<<", m="<<m<<endl;

    for (int i = 0; i < m; i++) {
        int d=2;

        cout << "i=" << i << ", d="<<d<< endl;

        pho[d] = true;
    }



    for (int i = 0; i < n - 1; i++) {
        int a, b;
        cin >> a >> b;
        adj[a].insert(b);
        adj[b].insert(a);
        degrees[a]++;
        degrees[b]++;
    }

    queue<int> next;
    for (int i = 0; i < n; i++) {
        if (degrees[i] == 0) {
            next.push(i);
        }
    }

    while (!next.empty()) {
        int node = next.front();
        next.pop();
        if (pho[node])
            continue;
        for (int neigh : adj[node]) {
            adj[node].erase(neigh);
            adj[neigh].erase(node);
            degrees[node]--;
            degrees[neigh]--;
            if (degrees[neigh] == 1)
                next.push(neigh);
        }
    }

    visited=new bool[n];
    memset(visited, 0, sizeof(bool) * n);

    pair<int, int> pivot = dfs(def);

    memset(visited, 0, sizeof(bool) * n);
    pair<int, int> end = dfs(pivot.second);

    int dist = end.first; //number of edges she only has to walk once

    int tree = n - 1; //number of edges in tree

    int otherdist = tree - dist; //number of edges she has to walk twice

    int total = dist + otherdist * 2;

    cout << total << endl;

    return 0;
}

这些行是错误的:

adj[a].insert(b);
adj[b].insert(a);

您需要使用ab作为键创建unordered_map实例,然后分别插入ba作为值。 如果需要键值对,则不需要向量集。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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