C++ STL stack pop operation giving segmentation fault

一曲冷凌霜 提交于 2019-12-23 01:50:05

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/26205633/c-stl-stack-pop-operation-giving-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!