I am very new to C++... I'm trying to implement a simple stack with Linked List..I know segmentation fault has to do with memory but all I did was make a stack with one element in it and it's only throwing "Segmentation fault: 11" that I have no clue where it came from. Here's my code:
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node* link;
};
Node* Push(int, Node*);
int main(){
struct Node* top = nullptr;
top = Push(3, top);
}
Node* Push(int data, Node* top){
struct Node* temp = (struct Node*) new Node();
temp->data = data;
temp->link = top->link;
top = temp;
return top;
}
struct Node* temp = (struct Node*) new Node();asNode* temp = new Node();. And intop->linkyou're dereferencing a null pointer leading to undefined behavior.temp->link = top->link;called throughtop = Push(3, top);inmainyou dereference a null pointer.topisnullptr, then this will cause a segfault:temp->link = top->link;You are dereferencing a null pointer there withtop->link. You need to check first iftopis a null pointer, and not do this when it is.temp->link = top;.