I performed the pop operation on S[position] stack and it's giving segment fault but the top operation giving the result without any error and the empty check also performed before the pop operation.
Can't figure out what is causing the problem.
#include<iostream>
#include<stack>
#include<stdlib.h>
using namespace std;
int main(){
int bar,position;
cout<<"Enter the number of bars: ";cin>>bar;
cout<<"Enter the position of the bar where you want to place: ";cin>>position;
position = position - 1;
stack<int> S[bar];
for(int i = bar; i>0; i--){
S[0].push(i);
}
S[0].pop();
for(int i = 1; i<bar; i++){
if(i == position){
S[i].push(1);
continue;
}
S[i].push(S[0].top());
S[0].pop();
}
for(int i = 1; i< bar; i++){
if(S[i].top() == 2){
if(!S[position].empty()){
cout<<S[position].top();
S[position].pop(); //This line generating segment fault
}
}
}
}
Output:
Enter the number of bars: 3 Enter the position of the bar where you want to place: 2 Segmentation fault (core dumped)
– WhozCraig Nov 11 '19 at 14:13– WhozCraig Nov 11 '19 at 14:26