ContestDestroyer's blog

By ContestDestroyer, history, 6 years ago, In English

A guy gave me this code:

#include<stdio.h>
#include<conio.h>
void main(void)
{
    int b;
    char a;
    scanf("%d",&b);
    scanf("%s",&a);
    printf("%d",b);
    getch();
}

I knew that he used the wrong specifier for char a, but this code ran, and after that, b's value that i had typed before was changed to another value. I'm very curious about this case, can someone show me how this is done?

  • Vote: I like it
  • -16
  • Vote: I do not like it

»
6 years ago, # |
Rev. 2   Vote: I like it +10 Vote: I do not like it

I'm afraid you are completely missing that scanf fills the memory at the variable's location. Attempting to fill a's memory for the size larger than this variable has leads you to unpredictable spoiling of memory belonging to other variables, function return address etc. You'd better lay your hands on Kernighan & Ritchie book about C (2-nd edition is free on the internet) and learn the language a bit. Seriously, this is not the question worth of asking at this site :(

P.S. other option is to switch to C++ / Java / Python — they are designed in a way which reduces or eliminates the chance of such low-level mistakes...

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

b is placed just after a in memory. So, when you're reading the string into a address, it actually reads that string into a (first symbol) and b (the rest). So bytes of b become overwritten with bytes from the read string.