[英]prefix notation c++, segmentation fault (stack and queue)
我试图弄清楚为什么会出现分段错误,我的猜测是它在我的递归函数中,它简化了前缀表示法操作。
例如:
“m + 4 4”返回:“+ 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)。 导致代码试图访问字符串数组之外的内存。感谢Struthersneil发现了这个缺陷!
请查看我的旧 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() 对字符串数组中的每个字符调用 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.