i have some question.
I try this code and recieve “Segmentation fault” error:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
struct Stack {
int value;
Stack *next;
};
void push(Stack* top, int value) {
Stack *ntop = new Stack;
ntop->value = top->value;
ntop->next = top->next;
top->next = ntop;
top->value = value;
}
int pop(Stack* top) {
int val = top->value;
top->value = top->next->value;
top->next = top->next->next;
return val;
}
int main()
{
Stack *top;
top->next = NULL;
push(top, 20);
cout << pop(top);
}
[10:40:46] [~] >> g++ 3.cpp -o 3 && ./3 Segmentation fault
but if i add const char* test = “”; before Stack *top; it works normal:
int main()
{
const char* test = "";
Stack *top;
top->next = NULL;
push(top, 20);
cout << pop(top);
}
[10:47:33] [~] >> g++ 3.cpp -o 3 && ./3 20
where my mistake?
The problem is here:
You are referencing an uninitialized pointer. That’s undefined behavior. So anything can happen and it may not be consistent with surrounding code.
I suppose you forgot to actually allocate something for
top.*Though I’d want point out that you’ll still have memory leaks inside the code.