列表附加功能中的错误

error in list appened function

本文关键字:错误 功能 列表      更新时间:2023-10-16

我在Visual Studio和G 中都遇到了错误,我尝试了GDB,但没有从中获得任何有用的东西

Visual Studio = in array2.exe中的0x00cd464f intherped exception。

gdb给出=程序接收到信号sigsegv,分割故障。列表中的370x000000010040118f :: append(this = 0x23aa80,x = 6)在main.cpp:61

      #include <iostream>
#include <stdlib.h>
// "arraylist.h"
#include <new>
//#include "myList.h"
using namespace std;

struct node{
    int data;
    node* next;
};
struct list{
    node* head;
    void append(int x);
};
int main()
{
    list L;
    L.append(6);
    node* cur = L.head;
    while (cur->next != 0)
    {
        std::cout << cur->data << std::endl;
        cur = cur->next;
    }
    return 0;
}
void list::append(int x)
{
    node* tmp = new node;
    node* cur = head;
    tmp->data = x;
    tmp->next;
    if (cur->data == 0)
    {
        head = tmp;
    }
    else{
        while (cur->next != 0)
        {
            cur = cur->next;
        }
        cur->next = tmp;
    }

}

一些提示:

  1. 您不初始化L.head(谢谢@Alan Stokes)。

  2. 您不是初始化tmp->next

  3. cur->data == 0不是检查列表是否为空的正确方法。

您的代码无效,因为当创建列表的对象

时,列表的数据成员头未初始化。
struct list{
    node* head;
    void append(int x);
};
int main()
{
    list L;  // <== head is not initialized.

您可以写作

    list L = { 0 };

struct list{
    node* head = 0;
    void append(int x);
};

in

if (cur->data == 0)
{
    head = tmp;
}

您正在尝试访问新创建的list对象的头部,这意味着您正在使用非初始化的指针。这意味着,每当您解除它时,您都将访问内存的一个不确定的部分,在这种情况下,您不应该访问一部分(这会导致访问违规错误)。我建议在结构构造函数中使用NULL设置head,并在尝试访问它的每种方法中检查头是否为NULL(在这种情况下为list::append(int))。

list::list(){
   head = NULL;
}

当您使用list L;

时,该空构造函数被隐式称为