Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

c - strange behavior of scanf for short int

the code is as follows:

#include <stdio.h>
main()
{
    int m=123;
    int n = 1234;
    short int a;
    a=~0;
    if((a>>5)!=a){
        printf("Logical Shift
");
        m=0;
    }
    else{
        printf("Arithmetic Shift
");
        m=1;
    }
    scanf("%d",&a);
    printf("%d
", m);
}

after the line scanf("%d",&a); the value of m becomes 0.

I know it may be caused by the scanf: a's type is short and the input's type is int. But How can this affect the value of m ?

Thanks a lot !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...