Блог пользователя ContestDestroyer

Автор ContestDestroyer, история, 7 лет назад, По-английски

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
  • Проголосовать: не нравится

»
7 лет назад, # |
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...

»
7 лет назад, # |
  Проголосовать: нравится 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.

»
2 дня назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

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() .