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?
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...
b
is placed just aftera
in memory. So, when you're reading the string intoa
address, it actually reads that string intoa
(first symbol) andb
(the rest). So bytes ofb
become overwritten with bytes from the read string.It's a memory misuse problem, it happens when b is just after a in memory so the data inside b will be overwritten so u need to be careful using scanf() .