i created a stack program using link list
when i compile the program its not giving any error but when m running this program it giving error ="segmentation fault"
os: linux
compiler :g++
please help
code:
#include<iostream>
using namespace std;
struct node{ //creating structure for node
int data; //data field of node
node *next; //next pointer of node
};
class stack{ //class for creating stack
public:
node *top,*temp; //defining top for stack and temp variable also
stack(); //constructor for value of top
void push(int n); //function declaration for pushing element
int pop(int n); //function declaration for deleting element from stack
Tip #1: Please use code tags when posting code. By not using code tags, people become unmotivated to read your problem let alone the code itself.
Tip #2: Learn to use a debugger. There are many GUI front-ends for gdb out there to make debugging less painful for beginners.
Tip #3: Understand what the error actually means: "Segmentation fault" means that the program attempted to access an invalid location of memory (or at least the CPU did not allow it).
Now, on to your problem. Without even trying out your code, I can see that in the stack::stack() constructor, stack::top is set to NULL, while stack::temp is uninitialized. The first time stack::push is invoked, the if statement possibly succeeds. Then the next line of code attempts to write something to the data member of temp (which was uninitialized). This seems to be the problem here.
Recommendation: Your stack::stack() constructor must explicitly initialize the stack::temp data member.