I was trying this problem called valid parenthesis on leetcode.com when an error popped up saying this:
AddressSanitizer:DEADLYSIGNAL
=================================================================
==30==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x0000003783d6 bp 0x7ffe68231e10 sp 0x7ffe68231ca0 T0)
==30==The signal is caused by a READ memory access.
==30==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.
#3 0x7f427121b0b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
AddressSanitizer can not provide additional info.
==30==ABORTING
This is the code which generated the error
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string str) {
stack<char> s;
bool val=true;
for(int i=0;i<str.length();i++){
if(str[i]=='(') s.push(')');
else if(str[i]=='{') s.push('}');
else if(str[i]=='[') s.push(']');
else if(str[i]==')'||str[i]=='}'||str[i]==']'){
if(str[i]==s.top()) s.pop();
else if(str[i]!=s.top()) {
val=false;
break;
}
}
}
if(s.empty()) val=true;
else if(!s.empty()) val=false;
return val;
}
};
I don't understand this error and would be really helpful if someone gives a solution for this
Consider what would happen on this simple input
)
.Your program would call
s.top()
on an empty stack. That's an illegal operation and would explain why your program crashes.You should perhaps rewrite your code like this so you check whether the stack is empty before you call
s.top()
although I haven't tested this.