Is using the address of an uninitialized variable UB? [duplicate]

喜夏-厌秋 提交于 2019-12-23 17:50:28

问题


Is this small code UB?

void Test()
{
  int bar;
  printf("%p", &bar);  
}

IMO it's not UB, but I'd like some other opinions.

It simply prints the address of bar, even if bar has never been initialized.


回答1:


TL:DR No, your code does not invoke UB by using anything uninitialized, as you might have thought.


The address of a(ny) variable (automatic, in this case) has a defined value, so irrespective of whether the variable itself is initialized or not, the address of the variable is a defined value. You can make use of that value. ( if you're not dealing with pointers and doing double-dereference. :) )

That said, strictly speaking, you should write

 printf("%p", (void *)&bar);

as %p expects an argument of type pointer to void and printf() being a variadic function, no promotion (conversion) is performed. Otherwise, this is a well-defined behavior.

C11, chapter §7.21.6.1

p The argument shall be a pointer to void. [.....]




回答2:


Is this small code UB?

Yes, it's UB because the conversion specifier p requires a void-pointer.

On the other hand the code below does not invoke UB

void Test(void)
{
  int bar;
  printf("%p", (void*) &bar);  
}

as the address of bar is well defined independently whether bar itself got initialised.




回答3:


This behavior is well defined.

The address of the variable is known. The fact that it hasn't been explicitly initialized doesn't matter.



来源:https://stackoverflow.com/questions/39918506/is-using-the-address-of-an-uninitialized-variable-ub

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