'My program of infix to postfix gives runtime error

Below is an simple program to convert infix expression to postfix expression. It takes an infix expression in main program and after passing values in function converter, it returns a postfix expression as string.

#include<iostream>
#include<stdio.h>
#include<string>
#include <stack>
using namespace std;
int priority(char o) {
    if (o == '(' || o == ')')
        return -1;
    else if (o == '*' || o == '/')
        return 2;
    else if (o == '+' || o == '-')
        return 1;
    else if (o == '^' )
        return 3;
}
string converter(stack <char>s, string in) {
    string pf;
    int i;
    for (i = 0; i < in.length(); i++) {
        if ((in[i] >= 'a' && in[i] <= 'z') || (in[i] >= 'A' && in[i] <= 'Z') ){
            pf+= in[i];
        }
        else if (in[i] == '(') {
            s.push(in[i]);
        }
        else if (in[i] == ')') {
            while (s.top() != '(' && (!s.empty())) {
            char temp = s.top();
            pf += temp;
            s.pop();
            }
        }
        else  {
            if (s.empty()) {
                s.push(in[i]);
            }
            else {
                if (priority(in[i]) > s.top()) {
                    s.push(in[i]);
                }
                else if (priority(in[i]) == s.top()&&(in[i]=='^')) {
                    s.push(in[i]);
                }
                else {
                    while (priority(in[i]) <= s.top()&&(!s.empty())) {

                        char temp = s.top();
                        pf += temp;
                        s.pop();
                    }
                    s.push(in[i]);
                }
            }


        }
        
        }
    while (!s.empty()) {
        char temp = s.top();
        pf += temp;
        s.pop();
    }
        return pf;
    

}
int main() {
    string infix,postfix;
    cout << "input an infix expression"<<endl;
    cin >> infix;
    stack <char> s;
    postfix = converter(s, infix);
    cout << "Postfix expression is:" << postfix;
    return 0;
}

Every time I try to run the program, it gives runtime error. It works till taking an infix expression but the function aborts abnormally. I can't find the bug. I use visual studios. Is it a problem in my visual studios or a logic error, really don't know.



Solution 1:[1]

This bit:

while (priority(in[i]) <= s.top()&&(!s.empty()))

Accessing a stack's top when it's empty invokes undefined behavior, and that's exactly what's happening here, as priority(in[i]) <= s.top() will be checked first.

You should move the !s.empty() condition first. If it evaluates to true then the second condition will not be checked. This is called Short-circuit evaluation.

while (!s.empty() && priority(in[i]) <= s.top())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DarthQuack