【问题标题】:Linkedlist Memory Read Error链表内存读取错误
【发布时间】:2014-10-13 21:31:28
【问题描述】:

我正在尝试创建一个链表,但我遇到了关于内存访问的问题。我调试代码,看看它在哪里出错,但无法解决它。使用'Add watch',可以看到next has unable to read memory 错误。

struct Node
{
    string Name;
    Node* next;
};

struct LinkedList
{
    Node* head = NULL;
    bool isX = true;
};


LinkedList* initX(string Arr)
{
    LinkedList* link = new LinkedList;
    for (int i = 0; i < 15; i++)
    {
        Node* temp = new Node;
        temp->Name = Arr[i];
        Node* ptr = new Node;
        ptr = link->head;
        if (link->head != NULL)
        {
            while (ptr->next)
            {
                ptr = ptr->next;
            }
            ptr->next = temp;
            temp->next = NULL;
        }
        else
            link->head = temp;
    }
    return link;
}
Unhandled exception at 0x008E8AF7 in ...exe: 0xC0000005: Access violation reading location 0xCDCDCDE9.

我该如何解决?

【问题讨论】:

  • 请注意Node* ptr = new Node; ptr = link-&gt;head 会泄漏内存。首先为ptr 分配内存,然后通过重新分配它来覆盖它所指向的内容。虽然这不是问题的原因。
  • 如果link-&gt;head == NULL 在你做link-&gt;head = temp 之后你仍然没有将link-&gt;next 设置为NULL
  • 如果您传递给 initX 的字符串小于 15 个字符,则此代码将失败。发布main()函数怎么样?
  • @0x499602D2 谢谢。 “link->next to NULL”是什么意思,我没用过。
  • @PaulMcKenzie 这个字符串是常量,所以不会失败

标签: c++ pointers memory-management linked-list


【解决方案1】:

if 语句的else 部分中将link-&gt;head 设置为temp 后,您不会将temp-&gt;next 设置为NULL,因此可以像使用temp-&gt;next具有未定义行为的价值。将此添加到您的 else 部分:

else {
    link->head = temp;
    temp->next = NULL; // or nullptr
}

如果您将两个temp-&gt;next = NULL 移动,将它们合二为一,并将其​​作为for 循环中的最后一条语句,实际上会更好。这就是为什么你不必对两种情况都做同样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2013-10-05
    • 2014-12-06
    • 1970-01-01
    • 2023-03-04
    • 2020-12-04
    相关资源
    最近更新 更多