前缀表示法 C++,分段错误(堆栈和队列)

prefix notation c++, segmentation fault (stack and queue)

本文关键字:堆栈 队列 错误 分段 表示 C++ 前缀      更新时间:2023-10-16

我试图弄清楚为什么我得到分割错误,我的猜测是它在我的递归函数中,它简化了前缀表示法操作。

例如:

"m + 44" 返回:"+ m 8">

在测试过程中,我得到一个分段错误信号:

以信号 11 (SIGSEGV( 退出

我相信问题出在我的回避功能"操作">

string Operate(stack<string> &S, queue<string> &Q)
{
S.push(Q.front());
Q.pop();
std::string::size_type sz;
string result = "";
if (IsOperator(S.top()) == true)
{
S.push(Operate(S, Q));
}
if (Q.empty() == false)
{
S.push(Q.front());
Q.pop();
if (IsOperator(S.top()) == true)
{
S.push(Operate(S, Q));
}
if (S.size() < 3)
return "wrong input";
string arg1 = S.top();
S.pop();
string arg2 = S.top();
S.pop();
string oper = S.top();
S.pop();
if (StringIsDigit(arg1) && StringIsDigit(arg2))
{
int a = stoi(arg1, &sz);
int b = stoi(arg2, &sz);
char o = oper.at(0);
int c = 0;
if (o == '+')
c = b + a;
else if (o == '-')
c = b - a;
else if (o == '*')
c = b * a;
else
return "e";
result = to_string(c);
}
else
result = oper + " " + arg2 + " " + arg1;
}
else
{
result = S.top();
S.pop();
}
return result;
}

或在函数 StringIsDigit 中:

bool StringIsDigit(string arg)
{
bool result = true;
for (int i = 0; i < arg.size() && result == true; i++)
{
if ((arg.size() != 1) && (arg.at(0) == '-') && (arg.at(i + 1) != ' '))
i++;
else
result = isdigit(arg.at(i));
}
return result;
}

链接到整个程序代码: https://pastebin.com/04pfE55N

答案很简单,我的错误:SEGFAULT 是许多人为我指出的从内存读取、分段错误、wiki 的错误。

段断层是什么时候发生的?当我的函数 StringIsDigit(( 试图弄清楚超过 2 个字符的负值是否是整数时。在"if 语句中,当检查字符串是否确实是整数时,比如 -100",我继续读取字符串,直到到达 arg 字符串的末尾,但使用 arg.at(i + 1(。导致代码尝试访问字符串数组外部的内存。感谢斯特拉瑟尼尔发现这个缺陷!

请查看我的旧 StringIsDigit(( 以找出我犯的一个值错误:

bool StringIsDigit(string arg)
{
bool result = true;
for (int i = 0; i < arg.size() && result == true; i++)
{
if ((arg.size() != 1) && (arg.at(0) == '-') && (arg.at(i + 1) != ' '))
i++;
else
result = isdigit(arg.at(i));
}
return result;
}

解决方案我想确保字符串是整数,因为我的算法支持表达式,例如 x+3。这意味着我需要遍历字符串,对字符串数组中的每个字符调用isdigit((。虽然"-"不是整数,但显然需要"-"来表示负整数,所以我做了一个有缺陷的检查,正如你在旧的StringIsDigit((中看到的那样。我没有使用该条件 if 语句,而是检查第一个字符 '-' 和第二个字符是否不是空格 '',然后我让 isdigit(( 函数完成其余的工作。

bool StringIsDigit(string arg)
{
bool result = true;
//I only need to check if the first is a '-' char and
//the next char is not ' '.
for (int i = 0; i < arg.size() && result == true; i++)
{
if ((arg.size() != 1) && (arg.at(0) == '-') && (arg.at(1) != ' '))
i++;
else
result = isdigit(arg.at(i));
}
return result;
}