【发布时间】:2013-06-20 21:40:37
【问题描述】:
我一直在尝试对计算器进行编程,但遇到了一个我无法修复的错误。一旦我输入要完成的计算,就会出现分段错误。我认为分段错误是内存不足,所以我尝试删除我的两个循环,假设它们是问题所在,但没有运气。
可能是我的 malloc 吗?
int calculator()
{
int exit = (int *)malloc(sizeof(int));
exit = 1;
while(exit == 1){
printf("Welcome to the calculator, please enter the calculation you wish to make, if you wish to exit type EXIT\n");
float *num1 = (float *)malloc(sizeof(float));
float *num2 = (float *)malloc(sizeof(float));
char operation = (char *)malloc(sizeof(char));
float *ans = (float *)malloc(sizeof(float));
char *string = (char *)malloc(10*sizeof(char));
scanf("%s", &string);
int result = strncmp(string, "EXIT", 10);
if(result == 0){
exit = 0;
}
else{
//scanf("%f%c%f", &num1, &operation, &num2);
int length = strlen(string);
int i;
for(i = 0; i <= length; i++){
printf("forever");
if(isdigit(string[i]) != 0){
num1 = string[i];
}
else{
operation = string[i];
}
}
printf("num1%f\n", num1);
printf("operation%c\n", operation);
printf("num2%f\n", num2);
if(operation == '+'){
*ans = *num1 + *num2;
}
if(operation == '-'){
*ans = *num1 - *num2;
}
if(operation == '/'){
*ans = *num1 / *num2;
}
if(operation == '*'){
*ans = *num1 * *num2;
}
if(operation == '^'){
*ans = (float)pow(*num1,*num2);
}
printf("Your answer is %f\n", ans);
}
}
return 0;
}
示例输出:
欢迎使用计算器,请输入您要进行的计算,如果您想退出输入EXIT 5+9 分段错误(核心转储) 进程返回 139(0x8B) 执行时间:2.611s
我使用 malloc 的原因是,当我退出 for 循环时,我分配给变量的值丢失了。虽然这并没有解决问题,但我觉得我的代码存在根本问题。
【问题讨论】:
-
首先考虑
scanf("%s", string);。正如凯尔所指出的,您的operation分配既不需要也不建议(大部分情况都是如此)。char operation;不是指针类型,因此不需要分配。它是一个纯粹的堆栈变量。我建议一个关于指针和格式化输入过程的好教程。 -
你能给我们一个示例输出吗?
-
在这里使用 GDB 或 Valgrind 非常有帮助。
-
如果你使用 GCC,你可以使用 -g 编译,然后使用 valgrind 查看失败的确切行。很可能是
scanf("%s", &string);,看看string已经是一个指针了。 -
@ImreKerr 谢谢,这有效
标签: c segmentation-fault