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

孤者浪人 提交于 2019-12-02 13:44:57

On AMD64 with the SysV calling convention (used by nearly every system but Windows), the first few arguments to a function are passed in registers. That's why you don't see them on the stack: They aren't passed on the stack.

Specifically, the first few integer or pointer arguments are passed in rdi, rsi, rdx, whereas the first few floating point arguments are passed in xmm0, xmm1, and xmm2. Since a is passed in xmm0 but printf attempts to read a number from rsi, you won't see any correlation between the number you supplied and what is printed out.


For future readers: Please note that what OP attempts to do is undefined behavior. ISO 9899:2011 specifies that an int should be passed for %d, but OP is trying to use it with a double (after default argument promotions). For that, OP should use %f instead. Using the wrong formatting specifier is undefined behaviour. Please do not assume that the observations OP make hold on your system or anywhere and don't write this kind of code.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!