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

迈克尔

我目前在使用 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在你的构造,这是从不同的变量head在你的list班级。所以类中head变量list是未初始化的,这就解释了你看到的 valgrind 错误(即Conditional jump or move depends on uninitialised value(s))。您希望构造函数初始化列表类中的变量。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章