对未定义行为的一些怀疑 [英] some doubts on undefined behaviour
问题描述
struct X
{
int x,y;
char c;
};
main()
{
struct X x,* px;
px =& x ;
printf("%d",* px);
}
我认为上面的代码是printf产生一个UB,因为它是期待的,我们正在为它提供一个类型为struct X的变量。
i只需要对此进行确认,这样我就可以对UB发表更多疑问。
因为它期待一个错字
实际上我想写因为它期待一个int 。
我认为你是正确的,因为编译器可以自由地传递参数,无论如何它我选择并且我知道我使用的一些编译器使用完全独立的方法来传递基本类型(像int)和复合类型(如结构)。如果编译器期望一个int并且传递了一个struct,那么它会查找错误的位置并且很可能在数据的无效内存位置。
在结构对象中,非位字段成员和位字段所在的单位具有按声明顺序增加的地址。指向适当转换的结构对象的指针指向其初始成员(如果该成员是位字段,则指向它所在的单元),反之亦然。结构对象中可能存在未命名的填充,但不是在其开头。
指向对象或不完整类型的指针可能会转换为指向不同对象或不完整类型的指针。如果生成的指针未针对指向类型正确对齐,则行为未定义。否则,当再次转换回来时,结果将等于原始指针。
有问题的函数调用是printf()。此函数属于特殊情况,其原型仅指定第一个参数的类型。所有其他参数都通过默认参数提升。我无法找到关于指针的默认参数提升的明确陈述,但可能性是擦除指针。指向结构的指针和指向int的指针之间的区别。
虽然不明智,但我认为OP发布的代码不是未定义的行为。
struct X
{
int x,y;
char c;
};
main()
{
struct X x,*px;
px=&x;
printf("%d",*px);
}
I think the above piece of code printf produces a UB since it is expecting and we are providing it with a variable of type struct X.
i just need a confirmation on this so that i can post some more doubt on UB.
since it is expecting a typo
actually i wanted to write since it is expecting an int.
I think you are correct because the compiler is free to pass parameters in pretty much anyway it chooses and I know that some compilers I have used use completely separate methods to pass basic types (like int) and compound types (such as structs). If the compiler was expecting an int and was passed a struct then it would look in the wrong place and quite possibly at an invalid memory location for the data.
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (of if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.The function call in question is printf(). This function is something of a special case, its prototype only specifies the type of the first argument. All other arguments go through the default argument promotions. I couldn''t find a clear statement of precisely what the default argument promotion is for pointers, but odds are it "erases" the distinction between a pointer-to-struct and a pointer-to-int.
Although ill-advised, I believe the code posted by the OP is not undefined behavior.
这篇关于对未定义行为的一些怀疑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!