Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Got an segment error and not sure what causes it

#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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

  1. 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 for vIn_b and ‘/‘ for the operator.

  2. You don’t have a default: clause in your switch 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading