C++STL堆栈弹出操作导致分段错误

C++ STL stack pop operation giving segmentation fault

本文关键字:分段 错误 操作 堆栈 C++STL      更新时间:2023-10-16

我在C++中从这个链接实现了一个编程问题,但我的代码在pop()操作中出现了分段错误。我对C++还很陌生,似乎自己也找不到错误。

#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();
        }
}

谢谢你的帮助。

此行

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

是导致segfault的原因。在尝试访问top之前,您必须检查堆栈是否为空,因为在空堆栈上缩放top会调用UB。

在空容器上调用pop_back是未定义的。默认情况下,std::stack使用std::deque,请参见std::deque::pop_back: