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;
}
Ethan
  • 1
  • struct Node* top = nullptr; why do you point to a nullptr, I think this could cause your error – Poder Psittacus Jun 27 '22 at 08: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**. – Jason Jun 27 '22 at 08:36
  • In `temp->link = top->link;` called through `top = Push(3, top);` in `main` you dereference a null pointer. – collapsar Jun 27 '22 at 08: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. – Jesper Jun 27 '22 at 08:38
  • *I have no clue*. There two possibilities here, either you still have a lot to learn about pointers, or you aren't looking at the code you wrote properly. I suspect it's mostly the latter. It's obvious to anyone else looking at the code that `top->link` is the problem, but you've convinced yourself that the code you wrote is correct, and you can't shake that conviction no matter how many times you look at your own code. – john Jun 27 '22 at 08:49
  • 2
    Incidentally (no one seems to have mentioned this) the correct code is `temp->link = top;`. – john Jun 27 '22 at 08:56

0 Answers0