【问题标题】:Linked-list in c++C++中的链表
【发布时间】:2013-10-27 18:06:41
【问题描述】:

我在使用 c++ 中的链表时遇到了问题。 我的课看起来像这样:

class list {
    private: struct node {
        node * next;
        int val;
    };
    node * head;
    node * current;
    public: list();
    list(const list & l);
    list & operator = (const list & l);~list();
    void insert(int a);
    void goToHead();
    int getCurrentData();
    void advance();
    bool moreData();
};

我不会在这里描述所有函数,我确信它们工作正常但是有 operator = 的声明:

list & list::operator = (const list & l) {
    if ( & l == this) return *this;
    current = NULL;

    node * src, * * dst;
    head = ( * this).head;

    src = l.head;

    dst = & head;
    while (src) {
        if (!( * dst)) { * dst = new node;
        }
        ( * dst) - > val = src - > val;

        if (src == l.current) current = * dst;
        src = src - > next;

        dst = & (( * dst) - > next);
    }
    while (( * dst) != NULL) {
        node * t = ( * dst) - > next;
        delete * dst;
        ( * dst) = t;
    }
    return *this;
}

它必须将值从一个列表复制到另一个,添加节点或在必要时删除它们。如果列表相等或第二个更长(因此它必须删除节点),它可以工作。但是什么时候应该添加一些节点然后:

==4582== Conditional jump or move depends on uninitialised value(s)
==4582==    at 0x8048C52: list::operator=(list const&) (list.cpp:103)
==4582==    by 0x804891B: main (testlist.cpp:38)
==4582==  Uninitialised value was created by a heap allocation
==4582==    at 0x402B9B4: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4582==    by 0x8048BDE: list::operator=(list const&) (list.cpp:93)
==4582==    by 0x804891B: main (testlist.cpp:38)

我不知道这个声明有什么问题。感谢您的帮助。

抱歉,如果格式错误,我遇到了一些 chrome 问题,这就是原因。也许有一些例子,但是我必须使用这个,我有一个任务要这样做,我的意思是我有代码示例,只需要完成它。我仍然有同样的问题: 第 93 行是:

 * dst = new node;

而 103 只是最后一个右括号

}

再次感谢您的帮助。

【问题讨论】:

  • 请正确格式化您的代码。没有人会阅读看起来像 /dev/random 输出的代码。
  • 我会说有很多示例如何正确获取链表,无需再问...
  • @not-rightfold 完成 :)
  • 您能否指出代码中的第 103 行是哪一行?

标签: c++ linked-list valgrind


【解决方案1】:
  1. 请格式化您的代码并标记第 93 行和第 103 行
  2. 如果第 93 行是

    *dst=新节点;

和 103

node *t=(*dst)->next;

您可能希望将 dst->next 发送到 NULL(在您创建新的之后),否则它指向未初始化的内存。

【讨论】:

  • 是的,在某些情况下它可能会导致问题,但这次不会。即使没有删除,它也能正常工作,所以它必须是别的东西。
猜你喜欢
  • 1970-01-01
  • 2015-05-06
  • 2021-06-26
相关资源
最近更新 更多