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.
This line
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.Calling
pop_back
on an empty container is undefined.std::stack
usesstd::deque
by default, see std::deque::pop_back: