c++ - 链表的复制版本溢出

标签 c++ copy-constructor access-violation

我有一个链表类。 它包括一个复制构造函数:

LinkedListStorage(const LinkedListStorage &other) :root(NULL)
{
    size = other.size;
    count = other.count;
    node *cur = other.root;
    node *end = NULL;

    while(cur->next != NULL)
    {
        node* x = new node;
        x->word = cur->word;

        if(!root)
        {
            root = x;
            end = root;
        }
        else
        {
            end->next = x;
            end = x;
        }

        cur = cur->next;
    }
}

在类中,我通过一种将链表写入文件的方法来运行它,但是虽然该方法适用于原始列表,但列表的复制版本会导致访问冲突,逐句通过列表的最终条目复制的列表按预期指向 0x00000000,但是当它到达写入函数时,最后一个节点的指针最终指向 0xcdcdcdcd,在尝试复制和使用写入函数之间没有代码运行,因此它必须是复制构造函数,但我终究无法弄清楚哪里出了问题。

在此先感谢您的帮助!

最佳答案

如果没有看到类的其余部分很难说,但也许你需要初始化 x->next,即

node* x = new node;
x->word = cur->word;
x->next = NULL;

关于c++ - 链表的复制版本溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416609/

相关文章:

c++ - DirectX 11 访问冲突

c++ - Variadic 模板在目标文件中有重复的符号?

c++ - 如何将 BOOST_BIND_OPERATOR( !=, not_equal ) 与未定义 != 运算符的类一起使用

C++ std::deque 复制构造函数问题

c++ - 复制构造函数错误 : the object has type qualifiers that are not compatible with the member function

C++ 动态数组访问冲突

c++ - 读取 DICOM 文件时在 Release模式下出现 ITK 访问冲突错误,但在 Debug模式下不会出现 ITK 访问冲突错误

c++ - 如何修复 "non-aggregates cannot be initialized with initializer list” < map >

c++ - 自动扣除失败并显示消息 "inconsistent deduction for auto return type"

c++ - 如何为具有自引用指针的类实现复制构造函数/赋值运算符?