Im trying to make a linked list where the user has to enter in the values on their own in the console and then they show in the linked list. After entering the first value it shows an error "signal: segmentation fault (core dumped)", how do i fix it. Im a begginer at c++ so i really have no idea of how to fix this, all help is greatly appreciated. Heres the code:
#include <iostream>
using namespace std;
class Node{
public:
int value;
Node *next;
public:
Node(int value, Node *next = nullptr) {
this->value = value;
this->next = next;
}
int getValue() {return this->value;}
Node *getNext() {return this->next;}
void setNext(Node*next) {this->next = next;}
};
class LinkedList {
private:
Node *head;
public:
LinkedList() {
this->head = nullptr;
}
~LinkedList() {
while(this->head != nullptr) pop();
}
friend std::ostream & operator <<(std::ostream &os, const LinkedList &rhs) {
for(Node *curNode = rhs.head; curNode != nullptr; curNode = curNode->getNext()) {
os << curNode->getValue();
if (curNode->getNext() != nullptr) os << "";
}
return os;
}
void push(int value) {
this->head = new Node(value, this->head);
}
int pop() {
int value;
if (this->head != nullptr) {
value = this->head->getValue();
Node *temp = this->head;
this->head = this->head->getNext();
delete temp;
} else {
throw std::range_error("List is empty!");
}
return value;
}
};
void append(Node** head_ref, int new_data)
{
Node* new_node = new Node((*head_ref)-> value);
Node *last = *head_ref;
new_node->value = new_data;
new_node->next = NULL;
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->next != NULL)
{
last = last->next;
}
last->next = new_node;
return;
}
void printList(Node* n)
{
while (n != NULL) {
std::cout << n->value << " ";
n = n->next;
}
}
int main()
{
Node* head = NULL;
int a;
cout << "Please enter value 1#: ";
cin >> a;
append(&head, a);
int b;
cout << "Please enter value 2#: ";
cin >> b;
append(&head, b);
int c;
cout << "Please enter value 3#: ";
cin >> c;
append(&head, c);
int d;
cout << "Please enter value 4#: ";
cin >> d;
append(&head, d);
int e;
cout<<"Created Linked list is: ";
printList(head);
return 0;
}
-g(i.e. with debugging symbols) and run it withvalgrind. It will tell you where exactly your memory-related bug strikes. And sometimes it tells you even much more, e.g. in a use-after-free case it gives you the stack trace that allocated the previously existing block and the stack trace that freed it afterwards.append()function is rather confusing. (1) Make it so that it runs in constant time, not in linear time. This is always possible: You can (a) keep a pointer to the lastnextpointer or (b) prepend elements instead of appending them. Simplicity and efficiency makes debugging easier. (2) You don’t need anyiforforstatements in linked list manipulation. You don’t neednullptrchecks either. (3) Last but not least,valgrindmay tell you that you are dereferencing anullptrinwhile (last->next != NULL) ...during the first insertion.