My program should convert the invitation from infix to postfix. So far, through the debugger and other methods, I have found the exact point at which I segfault, but do not understand why.
Here is my code:
Here itop.h:
using namespace std; #include <cstdlib> #include <iostream> class sNode{ public: char data; sNode *next; }; class stack{ public: sNode *head; void push (char); sNode pop(); int rank(char); stack() { cout << "Initiliazing stack." << endl; } };
This is my itop.cpp file:
#include "itop.h" void stack::push (char a) { // cout << "Pushing " << a << endl; sNode *sn; sn = new sNode; sn->data = a; sn->next = head; head = sn; } sNode stack::pop() { // cout << "Popping stack." << endl; sNode *sn; sn = head; head = head->next; return *sn; } int stack::rank(char x) { int num = 0; // cout << "Checking rank." << endl; if(x == '\0') { num = 1; // cout << "Checking for null" << endl; return num; } else if(x == '+' || x == '-') { num = 2; // cout << "Checking if + or -" << endl; return num; // cout << "After return." << endl; } else if(x == '*' || x == '/') { num = 3; // cout << "Checking for * or /" << endl; return num; } else cout << "Error! Input not valid!" << endl; }
And here main.cpp:
using namespace std; #include <iostream> #include <cstdlib> #include <cstring> #include "itop.h" int main() { char *temp1; //Instantiating variables. char *temp2; temp1 = new char[20]; temp2 = new char [20]; stack s; do //Checking commands. { cout << "infix_to_postfix> "; cin >> temp1; if(strcmp(temp1, "quit") == 0) { return 0; } if(strcmp(temp1, "convert") != 0) { cout << "Error! Invalid command." << endl; } cin >> temp2; if(strcmp(temp1, "convert") == 0) { for(int i=0; i<sizeof(temp2); i++) { if(isdigit(temp2[i])) { cout << atoi(&temp2[i]); } else if(s.rank(temp2[i]) < s.rank(s.head->data)) { sNode temp = s.pop(); cout << temp.data; } else { s.push(temp2[i]); } } } else { cout << "Error! Command not supported." << endl; } }while(strcmp(temp1, "quit") != 0); return 0; }
Function called in
else if(s.rank(temp2[i]) < s.rank(s.head->data))
And the problem is here:
else if(x == '+' || x == '-') { num = 2; // cout << "Checking if + or -" << endl; return num; // cout << "After return." << endl; }
In particular, right before num returns, I get the error "Segmentation failed (core dumped)". I used gdb, and all I know is right after "Check if + or -" I see "$ 1 = 2". I do not quite understand what this means, but this is what I want to return.
Thank you for your help.
source share