AddressSanitizer:DEADLYSIGNAL 尝试使用堆栈运行代码以获取有效括号问题集时出现 DEADLYSIGNAL 错误

rit*_*raj 1 c++ segmentation-fault address-sanitizer

我在 leetcode.com 上尝试这个名为“有效括号”的问题时,弹出了一条错误消息:

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
Run Code Online (Sandbox Code Playgroud)

这是生成错误的代码

#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;
    }
};
Run Code Online (Sandbox Code Playgroud)

我不明白这个错误,如果有人为此提供解决方案,将会非常有帮助

joh*_*ohn 5

考虑一下这个简单的输入会发生什么)

您的程序将调用s.top()空堆栈。这是一个非法操作,可以解释为什么你的程序崩溃。

您也许应该像这样重写代码,以便在调用之前检查堆栈是否为空s.top()

if (!s.empty() && str[i] == s.top())
{
    s.pop();
}
else
{
    val=false;
    break;
}
Run Code Online (Sandbox Code Playgroud)

虽然我还没有测试过这个。