【问题标题】:AddressSanitizer:DEADLYSIGNAL地址消毒剂:DEADLYSIGNAL
【发布时间】: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


【解决方案1】:

如果您有输入字符串"(some text)",您的条件S[i] == 40 &amp;&amp; count++ &gt; 0 将始终评估为假。当S[i]=='(' 为真时,count++ &gt; 0 为假,因为count 在比较后递增。但是,count 会递增,因此第二个条件 S[i] == ')' &amp;&amp; count-- &gt; 0 最终会为真。然后你点击st.pop()。由于st为空,会出现问题。

此外,如果您修复代码,例如通过写S[i] == 40 &amp;&amp; ++count &gt; 0它不会像名字所暗示的那样删除括号

【讨论】:

    【解决方案2】:

    感谢您的帮助。它试图弹出一个空堆栈。

    错误 - if(S[i] == 41 &amp;&amp; count-- &gt; 0)

    更正 - if(S[i] == 41 &amp;&amp; count-- &gt; 1)

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 1970-01-01
      • 2017-09-17
      • 2023-03-23
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 2021-03-07
      • 2021-02-08
      相关资源
      最近更新 更多