问题描述
这个小码是UB吗?
void Test()
{
int bar;
printf("%p", &bar);
}
IMO 不是 UB,但我想要一些其他的意见.
IMO it's not UB, but I'd like some other opinions.
它只是打印bar
的地址,即使bar
从未被初始化.
It simply prints the address of bar
, even if bar
has never been initialized.
推荐答案
TL:DR 不,您的代码不会像您可能那样使用任何未初始化来调用 UB有想过.
TL:DR No, your code does not invoke UB by using anything uninitialized, as you might have thought.
a(ny) 变量的地址(在这种情况下是自动的)有一个 defined 值,所以无论变量本身是否被初始化,变量的地址都是一个 定义值.您可以利用该值.(如果您不处理指针和进行双重取消引用.:) )
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
需要一个指向 void
和 printf()
的类型指针的参数是一个可变参数函数,没有提升 (转换).否则,这是一个明确定义的行为.
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
,章节 §7.21.6.1
C11
, chapter §7.21.6.1
p
参数应该是一个指向 void
的指针.[……]
这篇关于是否使用未初始化的变量 UB 的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!