【发布时间】:2021-12-28 07:19:22
【问题描述】:
我想知道提供的示例在 C 中是否安全(无 UB):
typedef struct {
uint32_t a;
} parent_t;
typedef struct {
parent_t parent;
uint32_t b;
} child_t;
typedef struct {
uint32_t x;
} unrelated_t;
void test_function(parent_t* pParent) {
((child_t*)pParent)->b = 5U; // downcast is valid only if relation chain is valid
}
int main()
{
child_t child;
unrelated_t ub;
test_function((parent_t*)&child); // valid upcast?
test_function((parent_t*)&ub); // probably UB?
return 0;
}
由于显式转换,没有保证和良好的类型检查,但只要传递了正确的参数,这应该可以正常工作吗?
【问题讨论】:
-
"...这应该可行。" 什么应该可行?如果您的意思是保证
child和ub在内存中的相对位置 - 没有。 -
@WeatherVane 我想他们是在问
parent是否保证在child的偏移量为0,以及指针在两个方向上的转换是否有效。 -
@akimata 当你说“应该工作”时,打算发生什么?请使用输出显示预期结果。 C语言中的“继承、向上转换和向下转换”是什么意思?
-
@HolyBlackCat - 正是我所要求的,如果我可以安全地在孩子体内上下投掷。 Ub 只是编译器不会抱怨的一个例子,但行为很确定是未定义的,我不确定是否有更清洁/更安全的解决方案来捕获此类错误。
-
你知道
unions吗?
标签: c language-lawyer