简体   繁体   中英

why am i getting for the following code AddressSanitizer: SEGV on unknown address error

'''
#include<stack>
using namespace std;
class Solution {
public:
    bool isValid(string s) {
        stack<char> mystack;
        char c;

        for(int i=0;i<= s.length();i++){


            if(s[i]=='(' || s[i]=='{' || s[i]== '[')
                mystack.push(s[i]);
            if(i!=0){
            switch (s[i]){
               case ')':
                   if(mystack.top()== '(')
                       mystack.pop();
                   else return false;
               case '}':
                   if(mystack.top()== '{')
                       mystack.pop();
                   else return false;
               case ']':
                   if (mystack.top()== '[')
                       mystack.pop();
                   else return false;

           }
            }
            if(i==s.length() && !mystack.empty())
                return false;


        } 
        return true;
    }
};'''

I dont know why but Iam getting this error AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x000000383dd4 bp 0x7ffc40c5d970 sp 0x7ffc40c5d860 T0) with hint ** address pointing to zero page** can someone please explain why iam getting this and how to resolve this. THANKS in advance!

This code contained so many bugs. But the cause of the error actually was that inside the if condition of switch case

if( mystack.top() )

here I am accessing the top element of my stack without checking if it even exist or not hence the unknown address. It should have been

if( !mystack.empty() && mystack.top())

This was compiler check if the address you are looking for exist or not if it does than only it will try to access the value.

I asked this as a noob programmer and after months of programming I debugged this myself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM