K Kimash
K Kimash

Reputation: 97

Why am I unable to add elements to this stack?

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?

Upvotes: 0

Views: 345

Answers (3)

wohlstad
wohlstad

Reputation: 28084

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. Why should I not #include <bits/stdc++.h>?
  2. Why is "using namespace std;" considered bad practice?

Upvotes: 2

Naseef Chowdhury
Naseef Chowdhury

Reputation: 2464

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.

Upvotes: 0

Aarsh
Aarsh

Reputation: 420

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;
        }
                                                              
    }
    
}

Upvotes: 1

Related Questions