#include <stdio.h>
int main () {
int vIn_a, vIn_b, vIn_c;
char vOperator;
printf("Please enter a number\n");
scanf("%d", vIn_a);
printf("Please enter a number\n");
scanf("%d", vIn_b);
printf("Please enter a Operator\n");
scanf("%c", vOperator);
switch(vOperator){
case ' ':
vIn_c = (vIn_a vIn_b);
break;
case '-':
vIn_c = (vIn_a - vIn_b);
break;
case '/':
vIn_c = (vIn_a / vIn_b);
break;
case '*':
vIn_c = (vIn_a * vIn_b);
break;
}
printf("Result: %d %c %d = %d", vIn_a, vOperator, vIn_b, vIn_c);
return 0;
}
Just trying to figure this out, i ran gdb. But not sure what my debugger is telling me at this point. Maybe im overlooking it? Debugger: Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7c60d36 in ?? () from /usr/lib/libc.so.6
So what is causing this segmentation fault guys? Im learning C and im lost.
Thanks in advance.
CodePudding user response:
When you use scanf()
, you don't pass the variable into which you want to store the value, you pass a pointer to the variable.
So, for instance, instead of scanf("%d", vIn_a);
, you need scanf("%d", &vIn_a);
- note the '&
'!
The effect of the scanf()
calls, as you wrote them, was to pass an arbitrary number (whatever random content was in the uninitialised vIn_a
and vIn_b
) into scanf()
. It treated those random(ish) integer values as pointers. So when it wrote the user-contributed value into the "pointer" it has been passed, it had the effect of:
*(int *)vIn_a = user_entered_value;
If you know your way around pointers, you'll know this is a recipe for disaster!
There are two more gotchas:
Your '
/
' operator doesn't check whether its divisor (vIn_b
) is zero, so it would be easy to crash with a divide-by-zero error if the user selected zero forvIn_b
and '/
' for the operator.You don't have a
default:
clause in yourswitch
statement, so if the user types something other than the operator characters you're checking for,vIn_c
will contain random rubbish as it's uninitialised by the time it's printed.
CodePudding user response:
You can use scanf function with &. For example; scanf("%d", &vIn_a);
For documentation : https://cplusplus.com/reference/cstdio/scanf/