试图用c++编写我自己的链表实现,在点击列表中的3个元素后编写segfault代码

Trying to write my own linked list impementation in c++, code segfaults after hitting 3 elements in the list

本文关键字:列表 3个 元素 代码 segfault c++ 我自己 自己的 实现 链表      更新时间:2023-10-16

我一直在尝试编写自己的链表实现,但当我尝试访问第三个元素或它之后的任何元素时,代码会出错。添加元素不会出错,但访问会出错。我在get()函数中找不到指针错误。

列表中的每个节点都存储(模板t的)数据和指向下一个节点的指针。我有两个函数,一个用于第一个元素,另一个用于任何后续元素。后续元素的get()函数总是segfault。我在函数中有一些调试消息,它们吐出了我无法解释的结果。例如,如果我对第二个元素,然后是第三个元素运行get()请求,代码不会segfault,但它确实返回了明显不正确的结果。我放置的调试消息表明,当第二个元素调用函数来检查第三个元素时,如果发生了segfault,就会发生segfault。尝试使用和不使用cout<lt;newList.get(2)<lt;endl;你会得到非常不同的结果。

一个可能的原因是指针存储-我让get()函数在循环通过时输出每个元素(第一个元素除外)的指针,并将它们与add()函数输出的指针进行比较,元素0和1的指针匹配,但2及以上的指针不匹配,我似乎不明白为什么会这样。

#include <iostream>
using namespace std;

template <class T> class myLinkedList{
T data;
myLinkedList<T> *next = NULL;
public:
myLinkedList(T input){
data = input;
}
void add(T input){
if(next == NULL){
myLinkedList<T> newItem(input);
next = &newItem;
cout << "adding to list, data is " << input << ", pointer is " << next << endl;
}else{
myLinkedList<T> nextEntry = *next;
nextEntry.add(input);
}
}

T getData(){
return data;
}
//the start  of the get function, only used by the first entry in the list
T get(int entry){
int currentPosition = 0;
if(entry == currentPosition){
return getData();
}else{
//defrefrence the pointer anc check the next entry
myLinkedList<T> nextEntry = *next;
return nextEntry.get(entry, ++currentPosition);
}
}
private:
//this vesion is the hidden, private vesion only used by nodes other than the first one
//used to keep track of position in the list
T get(int entry, int currentPosition){
//cout << currentPosition << endl;
if(entry == currentPosition){
return data;
}else{
//derefrence the pointer and check the next entry
cout << next << endl;
myLinkedList<T> nextEntry = *next;
currentPosition++;
T output = nextEntry.get(entry, currentPosition);
return output;
}
}

};
int main(){
myLinkedList<int> newList(3);
newList.add(4);
newList.add(5);
newList.add(7);
newList.add(9);
cout << newList.get(2) << endl;
cout << newList.get(3) << endl;
return 0;
}

结果显然是错误的——程序应该吐出两组macthing指针,以及数字5和7(列表元素)

您的主要问题之一是:

if(next == NULL){
myLinkedList<T> newItem(input); // <<<<<<<<<<<<<
next = &newItem;
cout << "adding to list, data is " << input << ", pointer is " << next << endl;
}

if作用域内的堆栈上分配一个项。然后你把下一个指向这个项目。但是项的生存期受此范围限制。一旦您退出作用域,此项就不再存在。您需要通过"new"或其他方法动态分配它。

我有了突破!遵循Serge的解决方案是有帮助的,但还需要一个更改——而不是在我的add函数的else块中创建函数引用,例如

myLinkedList<T> nextEntry = *next;
nextEntry.add(input)

我需要直接使用指针,就像在中一样

next->add(input)

我不知道我的指针/对象语法

相关文章: