why my variable's value changes (i noticed when using debugger that the value changed)?

183 views Asked by At

I am prompting the user for a card number and then applying some formula on this number but I noticed an expected change in the output as the variable's value changes during the running of the code without reassigning it the variable 'long card' value changes.

    long card = checkNumber();
    const long card_to_use = card;
    char card_name[0];
    int cardL = (floor(log10(card)) + 1);
    const int first_two_digits = card_to_use/myPow(10,cardL-2);
    const int first_digit = card_to_use/myPow(10,cardL-1);
    if(first_two_digits>=51 && first_two_digits<=55){
        strcpy(card_name, "mastercard");
    }else if (first_two_digits==37 || first_two_digits==34){
        strcpy(card_name, "amex");
    }else if(first_digit == 4){
        strcpy(card_name, "visa");
    }

the value changes when if(first_two_digits>=51 && first_two_digits<=55) is executed I don't know exactly why? I tried to capture the value of it in const long card_to_use from the beginning but it also changed actually changed to a 19 digit number which is also surprising. thanks for reading

p.s: I am using cs50 IDE

3

There are 3 answers

0
noot noot On

char card_name[0];

This array has zero space, specified by the [0]. When the program writes to the array it runs off the end, corrupting other things in the memory. Changing it to something like:

char card_name[20];

Would assign 20 char spaces in an array to work with, which looks like enough for your program.

0
Sagar On

You've declared card_name as a zero-length char array on the stack. The strcpy() call is probably clobbering the other variables on the stack (eg. card_to_use) due to overflow.

As to how this is happening before the call to strcpy() when the debugger is claiming you're at the line with if (...), that's probably due to optimization. You can disable optimization using the -O0 compile flag on gcc and clang. Note that in this case, optimization is likely not causing the call to occur before the condition check. Some instruction corresponding to the condition check is probably executing after the call to strcpy().

0
Jeremy Whitcher On

I believe the problem is the definition of card_name. char card_name[0] doesn't allocate any space for the characters copied during the strcpy() step.

Try changing char card_name[0] to char card_name[30].