### ContestDestroyer's blog

By ContestDestroyer, history, 5 years ago,

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?

• -16

 » 5 years ago, # | ← Rev. 2 →   +10 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...
 » 5 years ago, # |   0 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.