strange behavior of scanf for short int

后端 未结 5 2018
余生分开走
余生分开走 2020-12-11 10:25

the code is as follows:

#include 
main()
{
    int m=123;
    int n = 1234;
    short int a;
    a=~0;
          


        
5条回答
  •  自闭症患者
    2020-12-11 10:54

    The most likely reason for m being 0 in your snippet is because you assign m to have this value in the body of your if-statement, but since the code contains undefined behavior no one can say that for sure.


    The likely story about passing a short* when scanf expects an int*

    Assuming sizeof(short) = 2 and sizeof(int) == 4.

    When entering your main function the stack on which the variables reside would normally look something like the below:

      _
     |short int (a)   : scanf will try to read an int (4 bytes).
     |_ 2 bytes       : This part of memory will most
     |int       (n)   : likely be overwritten
     |                :..
     |
     |_ 4 bytes
     |int       (m)
     |
     |
     |_ 4 bytes
    

    When you read a %d (ie. an int) into the variable a that shouldn't affect variable m, though n will most likely have parts of it overwritten.


    Undefined Behavior

    Though it's all a guessing game since you are invoking what we normally refer to as "undefined behavior" when using your scanf statement.

    Everything the standard doesn't guarantee is UB, and the result could be anything. Maybe you will write data to another segment that is part of a different variable, or maybe you might make the universe implode.

    Nobody can guarantee that we will live to see another day when UB is present.


    How to read a short int using scanf

    Use %hd, and be sure to pass it a short*.. we've had enough of UB for one night!

提交回复
热议问题