【发布时间】:2011-12-12 11:23:49
【问题描述】:
我定义了一个联合如下:
union {
uintptr_t refcount;
struct slab_header *page;
} u;
page 指针保证在页面边界上对齐(很可能是 4096),并且永远不会是NULL。这意味着可能的最低地址将是4096。
refcount 将在0 .. 4095 内。
在创建封闭结构后,我可以拥有u.refcount = 0 或u.page = mmap(...)。
围绕这个联合的代码将是这样的:
if (u.refcount < 4096) {
/* work with refcount, possibly increment it */
} else {
/* work with page, possibly dereference it */
}
这是否总是保证在完全符合 POSIX 的实现上工作? uintptr_t 和 struct slab_header * 是否有可能具有不同的表示形式,例如,当 u.page == 8192、u.refcount < 4096 产生 true 时?
【问题讨论】:
-
假设两个usion成员是兼容的。如果 refcount 为 0 - 4095,那么当 refcount 为 0 时,页指针肯定为 NULL,因为 NULL 几乎总是被实现为 0 或 (void*)0。
-
“这总是保证有效吗?” - 由谁担保?按照标准,没有。通过任何给定的 C 实现自己的文档/ABI,几乎可以肯定是的。大概如果你打电话给
mmap,那么 Posix 中的保证就足够了,尽管我没有声称有一个。 -
@Steve:假设一个完全符合 POSIX 的实现?