C++ STL stack pop operation giving segmentation fa

2019-06-02 18:45发布

I implemented a programming question from this link in C++ but I am getting a segmentation fault in the pop() operation with my code. I am fairly new to C++ and can not seem to find the error myself.

#include<iostream>
#include<stack>

using namespace std;

void printNge(int *arr);

int main() {
        int arr[] = {1,4,2,6,3,8,7,2,6};

        printNge(arr);

        return 0;
}

void printNge(int *arr) {
        stack<int> st;

        st.push(arr[0]);

        for(int i=1; i<9;i++) {
                while((st.top() < arr[i]) && (!st.empty())) {
                        cout << "Element is:" << st.top() << "  NGE is:" << arr[i] << endl;
                        cout << "Removing element: " << st.top() << endl;
                        st.pop();
                }
                cout << "Pushing element: " << arr[i] << endl;
                st.push(arr[i]);
        }
        while(!st.empty()) {
                cout << "Element is:" << st.top() << "  NGE is:" << -1 << endl;
                st.pop();
        }

}

Thanks for the help.

2条回答
相关推荐>>
2楼-- · 2019-06-02 19:32

This line

while((st.top() < arr[i]) && (!st.empty())) {

is what is causing the segfault. You have to check the stack for being empty before you try to access top, as caling top on empty stack invokes UB.

查看更多
干净又极端
3楼-- · 2019-06-02 19:46

Calling pop_back on an empty container is undefined. std::stack uses std::deque by default, see std::deque::pop_back:

查看更多
登录 后发表回答