[英]Linked List Segmentation Fault
為什么這會導致SegFault錯誤? 我試圖用gdb運行回溯,但是它沒有給我任何幫助。 任何幫助將不勝感激,我已經在此工作了幾個小時了。
我的node.h
#ifndef NODE_H
#define NODE_H
#include <string>
using namespace std;
class Node
{
public:
Node(const string, const int) ;
~Node() { }
void setNext(Node *);//setter for the next variable
Node * getNext();// getter for the next variable
string getKey();// getter for the key variable
int getDistance(); // getter for the dist variable
private:
Node *next;
int dist;
string key;
};
#endif
我的Node.cpp
#include "node.h"
#include <string>
Node::Node(string k, int d){
key = k;
dist = d;
}
void Node::setNext(Node * n){
next = n;
}
Node * Node::getNext(){
return next;
}
string Node::getKey(){
return key;
}
int Node::getDistance(){
return dist;
}
我的清單
#ifndef LIST_H
#define LIST_H
#include "node.h"
class SLL
{
public:
SLL();
~SLL() { }
void Insert (string searchKey, int distance);
bool Delete (string searchKey);
void Print();
int Search(string searchKey);
private:
int count;
Node *head;
Node *iterator;
Node *temp;
};
#endif
我的List.cpp
#include "list.h"
#include <iostream>
SLL::SLL():head(0){}
void SLL::Insert(string searchKey, int distance){
Node * temp = new Node(searchKey, distance);
if(head == 0){
head = temp;
}
else{
temp->setNext(head);
head = temp;
}
}
bool SLL::Delete(string searchKey){
if(head == 0){
cout << "An attempt was made to delete a node from an empty list" << endl;
}
else{
Node* iterator = head;
Node* last = 0;
while(iterator != 0){
if (iterator->getKey() == searchKey){
break;
}
else{
last = iterator;
iterator = iterator->getNext();
}
}
if (iterator == 0){
return false;
}
else{
if(head == iterator){
head = head->getNext();
}
else {
last->setNext(iterator->getNext());
}
delete iterator;
}
}
}
void SLL:: Print(){
iterator = head;
while(iterator != 0){
cout << iterator->getKey() << "-" << iterator->getDistance() << endl;
iterator = iterator->getNext();
}
}
int SLL::Search(string searchKey){
}
我的main.cpp
#include "list.h"
#include "node.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
SLL * sll;
sll->Insert("test", 1);
sll->Insert("test2", 2);
sll->Delete("test");
sll->Print();
}
提示:分段錯誤發生在這里:
int main(int argc, char* argv[]) {
SLL * sll;
sll->Insert("test", 1); // BIG segfault here.
...
(沒有完整的答案,因為這看起來像是家庭作業。)
在您的主要功能中,指向SSL
的指針未初始化,但您取消了對其的引用。 這是未定義的行為。 在您的特定情況下,這會導致細分沖突。 嘗試更改您的代碼以在堆棧上創建一個SSL
對象:
int main(int argc, char* argv[]) {
SLL sll;
sll.Insert("test", 1);
// ...
}
或堆:
int main(int argc, char* argv[]) {
SLL * sll = new SLL();
sll->Insert("test", 1);
// ...
}
順便說一句,您永遠不要使用SLL
類的temp
, iterator
,...字段,也不要初始化它們。 在實現中,您定義了隱藏它們的局部變量,因此建議您刪除字段或在構造函數中對其進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.