【问题标题】:Read access violation on Linked List in C++C++ 中链表的读取访问冲突
【发布时间】:2016-04-01 17:47:19
【问题描述】:

我有一个非常简单的链表,我想在它上面执行函数,但是当我运行我的代码时,我不断收到“根”节点上的读取访问冲突错误。

这是我得到的错误(我在出现错误的代码行之后发表了评论):

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

这是结构:

struct node {
int value;
node* link;

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

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

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;
}

我不断收到的错误出现在我在代码中的 cmets 中提到的行中。

【问题讨论】:

  • 在循环之前说root == 0x12345root-&gt;next == NULL。您希望您的病情检查什么?
  • root 未初始化,但使用了其(随机、未初始化)值。
  • 您的代码对我来说很好用。您能否提供有关重现此错误的更多信息?
  • 如果root-&gt;next==NULL 它将进入循环,计数 1 然后变为 NULL,然后它应该停止遍历并且不给出错误,但根似乎仍然转到 NULL 并且仍然不退出

标签: c++ linked-list access-violation


【解决方案1】:

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

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 << " ";
}

【讨论】:

  • 这行得通,但是我在 main addnode(root,20) 添加的第一个元素在我打印列表时不显示,并且不计入计数函数(它只是消失了)
  • 用你当前的问题添加关于 SO 的新问题
猜你喜欢
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2016-09-02
相关资源
最近更新 更多