Short* 到 int* 之间的转换
假设在 32 位操作系统上,short
为 2 个字节,int
为 4 个字节。以下是未定义的行为吗?
short s = 42;
int *p = (int*)(&s);
Assuming short
is 2 bytes and int
is 4 bytes on a 32 bit OS. Is the following an undefined behavior?
short s = 42;
int *p = (int*)(&s);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您发布的代码不会表现出未定义的行为,但尝试读取
*p
会表现出未定义的行为。另外,根据int
和short
的对齐要求,转换的结果可能是未指定且不可逆的(参见 5.2.10 [expr.reinterpret.cast] / 7 )。参见 ISO/IEC 14882:2011 3.10 [basic.lval] / 10:
您尝试访问的对象是
short
,而*p
是int
类型的 glvalue,它不会不符合上述任何描述。No, the code that you have posted does not exhibit undefined behavior but attempting to read
*p
would. Also, depending on the alignment requirements ofint
andshort
, the result of the cast may be unspecified and irreversable (see 5.2.10 [expr.reinterpret.cast] / 7).See ISO/IEC 14882:2011 3.10 [basic.lval] / 10:
The object that you are trying to access is a
short
and*p
is a glvalue of typeint
which doesn't meet any of the above descriptions.您的代码直接位于 UB 领域,因为您正在读取两个未初始化的字节。
相反的情况
然而,由于小端架构的语义,
可能会起作用。 (这一切都假设编译器没有做任何愚蠢的事情)
来自维基百科:
所以,只要你是小端,相反的方向应该没问题。
但仍然是未定义的行为。
Your code is directly in the realm of UB, as you are reading two uninitialized bytes.
However, the opposite,
will probably work due to the semantics of the little endian architecture.
(This is all assuming the compiler doesn't do anything stupid)
From wikipedia:
So, as long as you are little endian, the opposite direction should be fine.
Still undefined behavior though.