开发者

Changing vector value causing seg fault

I am working on a school project for graphs and here I am doing a depth first search down the tree.

void wdigraph::depth_first(int v) const {
    static int firstv = -1;
    static bool *visited = NULL;

    if (firstv == -1) {
            firstv = v;
            vector<bool> visited(size);
            for (int i = 0; i < size; i++) {
                    visited[i] = false;
                    cout << visited[i] << endl;
            }
    }
    cout << label[v];
  visited[v] = true;

// visited[0] = true;

The first input value to the function is 0 (v = 0) and it crashes with that. size = 5. As you can see at the end of the code, I have tried to set visited to true manually with the same seg fault. When I remove all attempts to change v开发者_运维知识库isited, the program runs how it should normally without a seg fault.

Any ideas why this can't be modified? Also, there is more code but I have decided not to provide it unless necessary.


There are two different variables named visited in your code. Inside the if condition, visited is a vector, but outside this block, on the last line:

visited[v] = true;

visited refers to the bool *visited = NULL defined at the beginning of your code. The segfault occurs because you're trying to dereference a null pointer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜