本文介绍了将整数常量转换为指针类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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:
因此,只要不取消引用它就可以做到这一点,而且它不是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.
这篇关于将整数常量转换为指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!