讨论/题目交流/c的基本计算器溢出问题;/
c的基本计算器溢出问题;
//计算函数;
int count(char *sign, int a, int b)
{
	int sum;
	switch (*sign)
	{
	case'+':
		sum = b + a;
		break;
	case '-':
		sum = b - a;
		break;
	default:
		break;
	}
	return sum;
}

int calculate(char * s){
	int i = 0, top1 = 0, top = 0, n, a, b;   //top1 为ops指针, top 为ovals指针;
	int *ovals;
	char *ops; 
	n = strlen(s);
	ovals = (int *)malloc(sizeof(int)*(n + 1) / 2);
	ops = (char *)malloc(sizeof(char)*n);
	while (s[i] != '\0')
	{
	
		if (s[i] == '+' || s[i] == '-' || s[i] == '(')
		{

			ops[++top1] = s[i];
		}
		else if (s[i] == ')')  //为右括号时;
		{	
		   while (ops[top1]!='(') //将括号中所有的符号输出;
			{
				a = ovals[top];
				b = ovals[--top];
				ovals[top] = count(&ops[top1--], a, b);
			}
		   top1--;
			//将左括号出栈;
		}
		else if ('0' <= s[i] && s[i] <= '9')
		{
		
			ovals[++top] = atoi(&s[i]);  //字符转化为数字;
			if (ops[top1] == '+' || ops[top1] == '-')
			{
				a = ovals[top];
				b = ovals[--top];
				ovals[top] = count(&ops[top1--], a, b);  //运算完成后符号出栈.  
			}
		} 
		i++;
	}
	if (top1 != 0)
	{
		a = ovals[top];
		b = ovals[--top];
		ovals[top] = count(&ops[top1--], a, b);
	}
	return ovals[1];
}

在输入值为"0"时出现.AddressSanitizer: heap-buffer-overflow on address 0x602000000134 at pc 0x000000401df9 bp 0x7ffd3982b490 sp 0x7ffd3982b480 堆缓冲区的溢出;
但在visual studio 2017 中能得到正确的值.
单步调试结果.
QQ图片20200420093246.png

n是main() 函数中接收计算结果;
QQ图片20200420093358.png
|基本计算器 |224 |困难|
这是什么问题???

展开讨论
共 1 个讨论

ovals[++top] = atoi(&s[i]); //字符转化为数字;
这个地方top会先++到1,ovals的长度应该也只是1吧,这样你会出现溢出。

1