分段故障11链接列表
segmentation fault 11 linked list
我的班级通过实现圆形单链接列表来对约瑟夫斯问题进行模拟。我的代码编译,但是当它运行时,我会得到一个分段错误:构建列表后的11。到目前为止,我的调试使我意识到,当程序进入主函数循环的最后一个循环时,发生错误。我认为这与我首先使用的方式有关,但我不确定。任何帮助都很棒,谢谢。我正在用C 编码,如果不是很明显。
#include <iostream>
#include <string>
using namespace std;
/*
* Node structure used by the linked list.
*/
struct Node {
// The name stored in this node.
string name;
// A pointer to the next node in the list.
Node * next;
};
/*
* Build the linked list
*/
class LinkedList {
private:
//pointer to the head of the list
Node *head;
public:
// constructor for LinkedList
LinkedList(){
head = NULL;
}
/*
* Add the given value to the list, making it the head.
*/
void insert(string name){
// Remember where old head was
Node *oldHead = head;
// allocate a new node in memory
head = new Node;
// set new node's fields
head->name = name;
head->next = oldHead;
}
/*
* Remove the item on the top of the stack, returning nothing.
*/
void remove() {
// Remember what the new head will be
Node* newSecond = head->next->next;
// Deallocate the head from memory
delete head->next;
// Set the head to the new head
head->next = newSecond;
}
/*
* Shifts the head forward one node.
*/
void cycle(){
head = head->next;
}
Node* getHead(){
return head;
}
// This is the opposite of a constructor - a destructor! You (almost)
// never need these in Java, but in C++ they are essential because
// you have to clean up memory by yourself. In particular, we need to
// empty out the stack.
~LinkedList() {
// While there's a head node still left, remove the head node.
while (head != NULL) {
remove();
}
}
};
int main(){
//create the circular linked list
LinkedList circle;
int people;
cin >> people;
string soldier;
Node* first = circle.getHead();
//Insert all the names
for(int i = 0; i < people; i++){
cin >> soldier;
circle.insert(soldier);
}
//begin the killing
while(first->next != NULL){
circle.cycle();
cout << " killed " << endl;
Node* temp = first->next->next;
circle.remove();
first->next = temp;
}
}
该代码中的几个问题。首先是:
Node* newSecond = head->next->next;
如果 head->next
为null,则您将获得一个空指针解除。这导致崩溃。
但是,这种特殊崩溃的实际原因是:
while(first->next != NULL)
是一个无效的指针删除。在main()
的开头,您有:
Node* first = circle.getHead();
circle
在此时为空,因此 first
被分配为null。它一直保持无效,直到您在while
语句中将其取消。因此,您会崩溃。
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表