segment fault in my stack program using link list

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

};


stack::stack() //constructor definition
{
top=NULL;
}

void stack::push(int n) //push function definition
{

if(temp!=0) //checking stack is empty or not
{
temp->data=n;
temp->next=top;
top=temp;
}
else
{
cout<<"stack is overflow";
}
}

int stack::pop(int n) //function definition for deleting element
{
if(top=0)
{
cout<<"stack is underflow";
}
else
{
n=top->data;
temp=top;
top=top->next;
delete temp;
return n;

}
}

int main()
{
stack s; //creating object

s.push(1); //calling function push()
s.push(2);

s.pop(2); //call to function pop()

cout<<"element popped"<<s.pop(2);

return 0;
}

please help
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.
Last edited on
Topic archived. No new replies allowed.