使用链表时的c ++析构函数段错误

c++ destructor seg fault when using linked list

我目前在用 c++ 编码时遇到段错误,Valgrind 和 gdb 告诉我我的析构函数有问题

//implementing constructor and destructor
list::list(){
        node * head = NULL;
}
list::~list(){
        if(head != NULL){
        delete head;}
}

//some code in a function that deal with linked list

head = new node;
setnull(head);
node * temp;
temp = head;

//....
//after some insert

temp->next = new node;
temp = temp->next;
setnull(temp);//setting elements in the list to null and set node->next to null

主要

  list My_list;
        node * head=NULL;
        int i = 0;
        char next_move[20];

        My_list.build(head,i);

来自 Valgrind 的信息

==9921== Conditional jump or move depends on uninitialised value(s)
==9921==    at 0x108E14: list::~list() (list.cpp:7)
==9921==    by 0x10988D: main (main.cpp:4)
==9921== 
==9921== Conditional jump or move depends on uninitialised value(s)
==9921==    at 0x4C311F1: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9921==    by 0x108E29: list::~list() (list.cpp:8)
==9921==    by 0x10988D: main (main.cpp:4)
==9921== 
==9921== Invalid free() / delete / delete[] / realloc()
==9921==    at 0x4C3123B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9921==    by 0x108E29: list::~list() (list.cpp:8)
==9921==    by 0x10988D: main (main.cpp:4)
==9921==  Address 0x3 is not stack'd, malloc'd or (recently) free'd
==9921== 

有人可以帮忙吗?

几乎肯定是这个

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

应该是这个

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

在您的代码中,您在构造函数中声明了一个名为 head 的变量,该变量与 list class 中的 head 不同。因此 list class 中的 head 变量未初始化,这解释了您看到的 valgrind 错误(即 Conditional jump or move depends on uninitialised value(s))。您希望构造函数初始化列表 class.

中的变量

如果还有更多错误我也不会感到惊讶,因此修复该错误可能无法修复您的程序。但是试试这个修复,看看你的进展如何。