【发布时间】:2021-03-06 05:41:11
【问题描述】:
当我在 leetcode 的以下代码中使用 `st.pop() 时出现此错误:
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
代码如下:
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;
}
};
【问题讨论】:
-
我猜你调用
st.pop()时堆栈是空的。您可以通过添加一些代码行轻松检查。还有edit 并显示调用removeOuterParentheses的代码 -
首先,不要使用幻数。如果要查看字符是否为
'(',则使用S[i] == '('。第二,如果你pop时你的栈是空的怎么办? -
看看如果输入是
40, 41会发生什么。count递增,但在第一次迭代时没有任何东西被压入堆栈,... -
@Damien,我在处理问题时故意不推动第一次迭代的括号 - 删除最外层括号。
标签: c++ data-structures stack queue