C++ STL stack pop operation giving segmentation fault(C ++ STL堆栈弹出操作给出分段错误)
问题描述
我从 this link 在 C++ 中实现了一个编程问题,但我得到了一个我的代码在 pop() 操作中出现分段错误.我对 C++ 还很陌生,自己似乎找不到错误.
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();
}
}
感谢您的帮助.
推荐答案
这一行
while((st.top() < arr[i]) && (!st.empty())) {
是导致段错误的原因.在尝试访问顶部之前,您必须检查堆栈是否为空,因为在空堆栈上调用 top 会调用 UB.
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.
这篇关于C ++ STL堆栈弹出操作给出分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C ++ STL堆栈弹出操作给出分段错误
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
