gpt4 book ai didi

c - 什么时候访问指向 "dead"对象的指针有效?

转载 作者:太空狗 更新时间:2023-10-29 16:18:06 25 4
gpt4 key购买 nike

首先,澄清一下,我不是在谈论解除对无效指针的引用!

考虑以下两个示例。

示例 1

typedef struct { int *p; } T;

T a = { malloc(sizeof(int) };
free(a.p); // a.p is now indeterminate?
T b = a; // Access through a non-character type?

示例 2

void foo(int *p) {}

int *p = malloc(sizeof(int));
free(p); // p is now indeterminate?
foo(p); // Access through a non-character type?

问题

上述任一示例是否会调用未定义的行为?

上下文

这个问题是为了回应 this discussion 而提出的.建议是,例如,指针参数可以通过 x86 段寄存器传递给函数,这可能会导致硬件异常。

从 C99 标准中,我们了解到以下内容(强调我的):

[3.17] indeterminate value - either an unspecified value or a trap representation

然后:

[6.2.4 p2] The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.

然后:

[6.2.6.1 p5] Certain object representations need not represent a value of the object type. 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. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined. Such a representation is called a trap representation.

综上所述,我们对访问“死”对象的指针有哪些限制?

附录

虽然我在上面引用了 C99 标准,但我很想知道在任何 C++ 标准中行为是否不同。

最佳答案

示例 2 无效。你问题的分析是正确的。

示例 1 有效。结构类型从不持有陷阱表示,即使其成员之一持有。这意味着在陷阱表示会导致问题的系统上,结构分配必须实现为按字节复制,而不是逐成员复制。

6.2.6 Representations of types

6.2.6.1 General

6 [...] The value of a structure or union object is never a t raprepresentation, even though the value of a member of the structure or union object may bea trap representation.

关于c - 什么时候访问指向 "dead"对象的指针有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17024866/

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