C ++中链表的读取访问冲突

Read access violation on Linked List in C++

我有一个非常简单的链表,我想对其执行功能,但是当我 运行 我的代码时,我在 'root' 节点上不断收到读取访问冲突错误。

这是我得到的错误(我在我得到错误的代码行之后评论):

抛出异常:读取访问冲突。 根是 0xCCCCCCCC。 如果有这个异常的处理程序,程序可以安全地继续。

这是结构:

struct node {
int value;
node* link;

node(int val) {
    link = NULL;
    value = val;
}
};

首先,我在 main 函数中初始化链表,如下所示:

int main() 
{
node *root;

addnode(root, 20);
addnode(root, 1);
addnode(root, 50);


node *curr;
for (curr = root; curr->link != NULL; curr = curr->link) { // I get error here
    cout << curr->value << " ";
}
cout << endl;

cout << "Number of elements " << countlist(root) << endl;

getchar();
return 0;
}

调用的函数是(第一个添加节点,第二个计算列表中的节点数):

void addnode(node *&root, int val) {
if (root != NULL) { // I get error here
    node *temp=new node(val);
    temp->link = root;
    root = temp;
}
else
    root = new node(val);
}

int countlist(node *root) {
if (root != NULL) {
    int count = 0;

    do {
        count++;
        root = root->link;
    } while (root->link != NULL); // I get error here

    return count;
}
return 0;
}

我不断收到的错误是我在代码注释中提到的行。

避免此类问题的一个好习惯可能是在声明时初始化所有变量:

int main() 
{
   node *root = nullptr;
   // ...
}

另外,你不想:

node *curr;
for (curr = root; curr->link != NULL; curr = curr->link) {
    cout << curr->value << " ";
}

但是

for (node *curr = root; curr != nullptr; curr = curr->link) {
    cout << curr->value << " ";
}