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
未正确对齐怎么办?
根据C11标准6.3.2.3指针的第5段:
整数可以转换为任何指针类型。除非先前指定,否则结果是实现定义的,可能未正确对齐,可能未指向引用类型的实体,并且可能是陷阱表示。
因此,只要不取消引用它就可以做到这一点,而且它不是UB,但是发生什么情况取决于平台。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句