0

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;
}
6
  • struct Node* top = nullptr; why do you point to a nullptr, I think this could cause your error Commented Jun 27, 2022 at 8:36
  • 1
    In C++ you can write struct Node* temp = (struct Node*) new Node(); as Node* temp = new Node();. And in top->link you're dereferencing a null pointer leading to undefined behavior. Commented Jun 27, 2022 at 8:36
  • In temp->link = top->link; called through top = Push(3, top); in main you dereference a null pointer. Commented Jun 27, 2022 at 8:37
  • 3
    If top is nullptr, then this will cause a segfault: temp->link = top->link; You are dereferencing a null pointer there with top->link. You need to check first if top is a null pointer, and not do this when it is. Commented Jun 27, 2022 at 8:38
  • 2
    Incidentally (no one seems to have mentioned this) the correct code is temp->link = top;. Commented Jun 27, 2022 at 8:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.