Reputation: 45
I am getting this error when I use `st.pop() in following code in leetcode:
AddressSanitizer:DEADLYSIGNAL
=================================================================
==31==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x0000003a1925 bp 0x7ffd7b62dce0 sp 0x7ffd7b62dcd0 T0)
==31==The signal is caused by a READ memory access.
==31==Hint: this fault was caused by a dereference of a high value address (see register values below). Dissassemble the provided pc to learn which register was used.
#8 0x7f3d81a1e0b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
AddressSanitizer can not provide additional info.
==31==ABORTING
The code is as follows:
class Solution {
public:
string removeOuterParentheses(string S) {
stack<char> st;
int count=0;
string ns;
for(int i=0;i<S.size();i++)
{
if(S[i] == 40 && count++ > 0)
{
st.push(S[i]);
ns+=S[i];
}
if(S[i] == 41 && count-- > 0)
{
st.pop();
ns+=S[i];
}
}
return ns;
}
};
Upvotes: 1
Views: 13285
Reputation: 45
Thanks for helping out. It was trying to pop an empty stack.
Error - if(S[i] == 41 && count-- > 0)
Correction - if(S[i] == 41 && count-- > 1)
Upvotes: 1
Reputation: 1226
If you have an input string "(some text)"
your condition S[i] == 40 && count++ > 0
will always evaluate to false. When S[i]=='('
is true then count++ > 0
is false as count
gets incremented after the comparison. However, count
gets incremented such that the second condition S[i] == ')' && count-- > 0
will eventually be true. Then you hit st.pop()
. As st
is empty, it will cause a problem.
Also, if you fix your code, e.g. by writing S[i] == 40 && ++count > 0
, it won't remove parentheses as the name implies.
Upvotes: 2