将整数常量转换为指针类型 [英] Casting integer constant to a pointer type
问题描述
UB是否将任意整数常量转换为指向对象/函数类型的指针(例如在单元测试中使用)?
Is it UB to cast an arbitrary integer constant to a pointer to a object/function type (to use in unit tests for example)?
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;
}
我要为此编写单元测试:
I want to write unit test for it as follows:
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
对齐不正确怎么办?
The thing that I'm not sure about is (struct helper *) helper_ptr
. Is it UB? What if (uintptr_t) 2
is not correctly aligned?
推荐答案
根据C11标准6.3.2.3指针的第5段:
From the C11 Standard 6.3.2.3 Pointers, paragraph 5:
整数可以转换为任何指针类型.除非先前指定,否则结果是实现定义的,可能未正确对齐,可能未指向引用类型的实体,并且可能是陷阱表示.
An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
因此,只要不取消引用它就可以做到这一点,而且它不是UB,但是发生什么情况取决于平台.
So you can do it as long as you do not dereference it, and it is not UB, but whatever happens will depend on the platform.
这篇关于将整数常量转换为指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!