LeetCode有效括号问题运行时出现AddressSanitizer:DEADLYSIGNAL错误求助
Hey there! Let's break down why you're hitting that AddressSanitizer:DEADLYSIGNAL error and fix your code step by step.
What's Causing the Crash?
The error you're seeing is a segmentation fault (SEGV)—this happens when your program tries to access memory it doesn't have permission to use. In your code, the culprit is calling s.top() when the stack is empty.
For example, if your input is something like "]" (a single closing bracket), your loop will hit the else-if branch for closing brackets, but the stack s is completely empty at that point. Calling s.top() on an empty stack is undefined behavior, which triggers the memory access error.
Other Logic Issues in Your Code
On top of the crash, there's a subtle logic bug:
- After setting
val = falsewhen a bracket mismatch is found, you break out of the loop—but then you overwritevalbased on whether the stack is empty. This means cases like"([)]"(which is invalid) would incorrectly returntruebecause the stack ends up empty, even though there was a mismatch earlier.
Fixed Code
Here's the corrected version of your code with explanations of the changes:
#include <stack> using namespace std; class Solution { public: bool isValid(string str) { stack<char> s; 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 { // We've hit a closing bracket—first check if stack is empty if(s.empty()) { return false; // No matching opening bracket exists } // Check if the closing bracket matches the expected one if(str[i] != s.top()) { return false; // Mismatched brackets } s.pop(); // Match found, remove the expected closing bracket from stack } } // After processing all characters, stack must be empty (all opening brackets had matches) return s.empty(); } };
Key Changes Made:
- Check for empty stack before accessing
s.top(): When we encounter a closing bracket, we first verify the stack isn't empty—if it is, we immediately returnfalsesince there's no corresponding opening bracket. - Remove the redundant
valvariable: Instead of tracking a boolean flag, we returnfalseas soon as we find an invalid case (empty stack or mismatched bracket). This makes the code cleaner and avoids overwriting the result later. - Final check only returns stack emptiness: After processing all characters, an empty stack means every opening bracket had a matching closing bracket in the correct order—exactly what we need for a valid string.
This should fix the segmentation fault and resolve the logic errors in your original code.
内容的提问来源于stack exchange,提问作者rithnagaraj

