hi...following code is for postfix evaluation.....after executing the code i am getting segmentation fault error....can u help me to solve this error and what is segmentation error?

#include<iostream>
#include<string.h>
using namespace std;

class post_evaluation
{
	public:
	int val;
	post_evaluation *nxt;
		void push(int i);
		void add();
		void sub();
};
post_evaluation *top=NULL;
void post_evaluation::push(int i)
{
	post_evaluation *t;
	t->val=i;
	t->nxt=NULL;
	top=t;
}
void post_evaluation:: add()
{
	post_evaluation *t;
	t->val=top->val;
	top=top->nxt;
	t->val=t->val+top->val;
	t->nxt=top->nxt;
	top=t;			
}
void post_evaluation::sub()
{
	post_evaluation *t;
	t->val=top->val;
	top=top->nxt;
	t->val=t->val-top->val;
	t->nxt=top->nxt;
	top=t;
}

int main()
{
	post_evaluation o;
	char exp[100];
	int i=0;
	cout<<"Enter your expression....:\n";
        cin>>exp;
//	for(i=0;exp[i]!='\0';i++)                        
	while(exp[i]!='\0')
        {
		//cout<<";
        	switch(exp[i])
                {
                	case '+':
				o.add();
				break;
			case '-':
				break;
			case '*':
				break;
			case '/':
				break;
			default :
				if(exp[i]!='\0')
				{
					int x=int(exp[i]);
					  o.push(x);								
				}
				else
					cout<<"No expression......";
					break;
				
                }
        }
	cout<<char(top->val);
	i++;
}

Line 17, 24, 33 are all the same and they are all wrong for one very important reason. "post_evaluation *t;" declares a pointer to a post_evaluation object, but it is not initialized. So "t" points nowhere or anywhere, which is really the same thing. You cannot use t if it was not initialized or you will get a "segmentation fault" which means you are trying to access memory that was never allocated (this will happen if you dereference a NULL pointer or a pointer that is uninitialized and thus, whose value is outside the chunks of memory that are allocated for you).

So you need to create an object, dynamically, and get its address into t. This is how:

post_evaluation *t = new post_evaluation();

You will also need to write a destructor for your class in order to free all this memory of the linked-list. Such as:

post_evaluation::~post_evaluation() {
  if( nxt != NULL )
    delete nxt;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.