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
You've declared
card_nameas a zero-length char array on the stack. Thestrcpy()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 withif (...), that's probably due to optimization. You can disable optimization using the-O0compile 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 tostrcpy().