Home > Enterprise >  Why am I unable to add elements to this stack?
Why am I unable to add elements to this stack?

Time:05-24

The following code is giving me a runtime error for some reason I'm unable to figure out. We are iterating over the string a and whenever we encounter a char = (, we push 1 into the stack and whenever we encounter ) we remove an element from the stack.

#include <bits/stdc  .h>
using namespace std;
int main() {
    string a= ")()())";
    stack<int> st;

    for(int z = 0; z < a.length(); z  ){
        if(a[z] == '(') st.push(1);
        else st.pop();   
                                                              
        }
    
}

Can someone please explain why is it giving me a runtime error?

CodePudding user response:

At the first iteration (z==0) you will encounter a ')' character.
Since it is != '(', you will atempt to pop a stack which is still empty.
This is the cause for your runtime error.

Side notes:

  1. Better to avoid #include <bits/stdc .h> - see here: Why should I not #include <bits/stdc .h>?.
  2. Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.

CodePudding user response:

You are popping from the stack even if the stack is empty.

Your code should be something like this.

#include <bits/stdc  .h>
using namespace std;
int main() {
    string a= ")()())";
    stack<int> st;

    for(int z = 0; z < a.length(); z  ){
        if(a[z] == '('){ 
            st.push(1);
        }
        else if(!st.empty()){
            st.pop();
        }
        else{ 
            cout<<"The Stack is empty. Nothing can be poped out"<<endl;
            break;
        }
                                                              
    }
    
}

CodePudding user response:

You need to check the stack size before popping. Let's walk through your input -

string a= ")()())";

When z is 0 in the first iteration, a[z] = ')', so it will go the else condition of your below code -

#include <bits/stdc  .h>
using namespace std;
int main() {
    string a= ")()())";
    stack<int> st;

    for(int z = 0; z < a.length(); z  ){
        if(a[z] == '(') st.push(1);
        else st.pop(); // The root cause of the issue is here
                                                              
        }
    
}

That means it will try to pop the top element of your stack, but your stack is empty since you are yet to push anything on it. Popping from an empty stack is undefined behavior. You can fix the error by checking the size of the stack before popping from it like the below -

#include <bits/stdc  .h>
using namespace std;
int main() {
    string a= ")()())";
    stack<int> st;

    for(int z = 0; z < a.length(); z  ){
        if(a[z] == '(') st.push(1);
        else if (!st.empty()) st.pop();   
                                                              
        }
}

I am not sure what your program intends to do, but this will definitely fix the undefined behavior.

  • Related