gpt4 book ai didi

c++ - 休息;导致段错误

转载 作者:行者123 更新时间:2023-11-28 01:19:07 25 4
gpt4 key购买 nike

我正在使用堆栈进行括号检查。包含 break; 语句的 if else 语句之一导致段错误。

我尝试删除 break 程序运行正常但打印错误答案,因为需要 break 才能打印正确的输出。这种段错误的原因是什么?中断不访问任何内存单元。对吗?

Questions link

#include <iostream>
#include<stack>
using namespace std;

int main() {
//code
int n;
char c,comp;
cin>>n;
while(n--)
{
stack<char>s;
while(cin>>c)
{
if(c=='(' || c=='{'|| c=='[')
s.push(c);
else
{
comp=s.top();
if(c==')' && comp=='(')
s.pop();
else if(c==')' && comp!='(')
{
cout<<"not balanced"<<endl;
break; //this one, if i remove this no SIGSEGV
}


if(c=='}' && comp=='{')
s.pop();
else if(c=='}' && comp!='{')
{
cout<<"not balanced"<<endl;
break;
}


if(c==']' && comp=='[')
s.pop();
else if(c==']' && comp!='[')
{
cout<<"not balanced"<<endl;
break;
}


}

}

if(s.empty())
cout<<"balanced"<<endl;
}

return 0;
}

最佳答案

所以,first some background information on std::stack稍后将变得相关:

The programming-by-contract style would be that having a non-empty stack is a precondition of calling pop, and that calling a method without meeting its preconditions has an undefined outcome.

请注意,虽然我找不到来源说 s.top() 在堆栈中有 0 个元素时是错误的,但我假设它也是错误的出于同样的原因。

为什么这很重要?嗯,undefined behavior can do anything ,包括段错误。把它记在脑后。

所以,这段代码就在这里:

comp=s.top();

如果您遇到 s 为空的情况,您有来自 std::cin 的其他内容,会发生什么情况?例如,如果您在像这样设置的括号末尾有一个额外的 ) 会怎么样:

()()) // <-- extra )

() 抵消了,但是 ) 仍然存在。因此,当您尝试引用顶部时,那里什么也没有。这可能是导致崩溃的原因。

在尝试引用顶部之前,您需要检查这一行以确保 s 不为空:

if(!s.empty()) {
comp=s.top();
}

您也应该围绕 pop() 执行此操作:

if(c==')' && comp=='(' && !s.empty())
s.pop();

或者类似的东西。您的逻辑可能需要一些修改,但希望这能给您带来灵感。

关于c++ - 休息;导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57387399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com