【发布时间】:2019-04-19 15:47:20
【问题描述】:
将任意整数常量转换为指向对象/函数类型的指针(例如在单元测试中使用)是否是 UB?
struct helper; //opqaue, creation the structure is complicated
struct my_struct{
struct helper *h_ptr;
char another_member;
};
static inline struct my_struct *create_my_struct(struct helper *h_ptr, char am){
struct my_struct *m_ptr = malloc(sizeof(*m_ptr));
m_ptr->h_ptr = h_ptr;
m_ptr->another_member = am;
return m_ptr;
}
我想为它编写单元测试如下:
uintptr_t helper_ptr = (uintptr_t) 2; //How about this?
char am = 'a';
struct my_struct *ms_ptr = create_my_struct((struct helper *) helper_ptr, am);
//do asserts
我不确定的是(struct helper *) helper_ptr。是UB吗?如果(uintptr_t) 2 没有正确对齐怎么办?
【问题讨论】:
-
在你要取消引用之前没关系。
-
@Sandro 所以这里的对齐不是问题。我不确定。谢谢。
-
即使它没有正确对齐,如果你不取消引用它,你应该不会遇到问题。
-
@Sandro 我同意这一点,但不幸的是,当我尝试比较它们时,我会有 UB。