Given the state of the stack and registers, can we predict the outcome of printf's undefined behavior

前端 未结 2 1899
鱼传尺愫
鱼传尺愫 2021-01-29 17:09

Here is some simple C code for a class quiz:

#include 

int main() {
  float a = 2.3;
  printf(\"%d\\n\", a);
  return 0;
}

Comp

2条回答
  •  感动是毒
    2021-01-29 17:28

    You try to use %d for float:

    d specifier is used for signed decimal integer

    f specifier is used for decimal floating point

    Using wrong specifier leads to Undefined behavior

    You relied on address of an automatic variable:

    I try to predict the output by viewing the memory near a

    a is an automatic variable, its address changes every time you compile the code, so memory-near-a also changes every time you compile the code.

    So, "viewing the memory near a" also causes Undefined behavior.

    Solution:

    You have nothing to do with Undefined behavior (in this case), so just forget it for saving time, it will make your life easier.

提交回复
热议问题