gpt4 book ai didi

c - 结构的陷阱表示

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:51 26 4
gpt4 key购买 nike

我想详细了解陷阱表示概念。定义很清楚第 3.19.4 节:

an object representation that need not represent a value of the object type

好的,我想通过一些例子来尝试一下。

struct test_t{
uint64_t member;
};

struct test_t *test_ptr = malloc(sizeof(uint32_t));
struct test_t = *test_ptr; //1

我不认为 //1 会导致 UB 在这里,因为 Section 6.2.6.1:

If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined.

但是

The value of a structure or union object is never a trap representation, even though the value of a member of the structure or union object may be a trap representation.

我认为UB会由类似的东西引起

printf("Test.member = %lu\n", test.member);

但我不确定如何证明在这种情况下 member 的表示是一个陷阱。

最佳答案

member 没有陷阱表示,因为 uint64_t 没有陷阱表示。

7.20.1.1 Exact-width integer types

2 The typedef name uintN_t designates an unsigned integer type with width N and no padding bits. Thus, uint24_t denotes such an unsigned integer type with a width of exactly 24 bits.

没有填充位。从以下部分我们了解到:

6.2.6.2 Integer types

1 For unsigned integer types other than unsigned char, the bits of the object representation shall be divided into two groups: value bits and padding bits (there need not be any of the latter). If there are N value bits, each bit shall represent a different power of 2 between 1 and 2N - 1, so that objects of that type shall be capable of representing values from 0 to 2N - 1 using a pure binary representation; this shall be known as the value representation. The values of any padding bits are unspecified.53)

尽管注解 53 是非规范的,但它告诉我们那些填充位(如果存在)可用于陷阱:

53) Some combinations of padding bits might generate trap representations, for example, if one padding bit is a parity bit. Regardless, no arithmetic operation on valid values can generate a trap representation other than as part of an exceptional condition such as an overflow, and this cannot occur with unsigned types. All other combinations of padding bits are alternative object representations of the value specified by the value bits.

虽然值位永远不能包含非法的模式。

因此您无法在格式良好的程序中生成 uint64_t 的陷阱表示。请注意,您的程序由于越界访问而具有 UB,但这不是由陷阱表示的可能性引起的。它本身是未定义的。

关于c - 结构的陷阱表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53902225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com