c - 结构的陷阱表示

标签 c struct language-lawyer

我想详细了解陷阱表示概念。定义非常清楚第 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,因为第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/

相关文章:

c - 如何用C语言解决C2054问题

if-statement - Golang 模板变量 isset

可以优化这种不稳定的访问吗?

perl - 为什么在没有粗逗号和严格的 `use` 行上允许使用前导连字符选项?

c - c 中的位移位字符

对 getchar 和 scanf 感到困惑

c - 将字符串传递给 C 中的结构体

c - 了解对象表示

c - 在一个程序中混合使用 SCHED_FIFO 和 SCHED_RR?

C# - 值类型等于方法 - 为什么编译器使用反射?