【发布时间】:2016-12-22 20:20:28
【问题描述】:
我正在考虑编写一个内存分配器,并试图找出如何解决现代 C 对类型双关和别名的限制。只要分配器底层的缓冲区最初是从 malloc 检索的,因为 malloc 的指针没有声明的类型,我想我是清楚的。
过度对齐的字符缓冲区确实具有声明的类型。我不认为我可以将指针转换为任意类型,并且必须通过 char 指针仔细写入它,例如使用 memcpy。这很痛苦,因为我看不到通过 memcpy hack 向调用者隐藏写入的方法。
考虑以下几点:
#include <assert.h>
#include <stdalign.h>
#include <stdint.h>
#include <string.h>
static_assert(sizeof(double) == sizeof(uint64_t), "");
static_assert(alignof(double) == alignof(uint64_t), "");
int main(void)
{
alignas(alignof(double)) char buffer[sizeof(double)];
// effective type of buffer is char [8]
{
double x = 3.14;
memcpy(&buffer, &x, sizeof(x));
// effective type of buffer is now double
}
{
uint64_t* ptr = (uint64_t*)&buffer;
// effective type of buffer is still double
// reading from *ptr would be undefined behaviour
uint64_t y = 42;
memcpy(ptr, &y, sizeof(y));
// effective type of buffer is now uint64_t
}
{
double* ptr = (double*)&buffer;
// effective type of buffer is still uint64_t
uint64_t retrieve = *(uint64_t*)ptr; // OK
assert(retrieve == 42);
double one = 1.0;
*ptr = one; // Unsure if OK to dereference pointer of wrong type
// What is the effective type of buffer now?
assert(*ptr == one);
}
}
这是可行的,因为我可以努力确保每次自定义分配器返回一个使用 memcpy 写入的 void 指针,而不是强制转换为所需的类型。也就是替换
double * x = my_malloc(sizeof(double));
*x = 3.14;
与:
double tmp = 3.14;
void * y = my_malloc(sizeof(double));
memcpy(y, &tmp, sizeof(double));
double * x = (double*)y;
所有这些线路噪音都被编译器中的优化通道消除了,但看起来确实很傻。是否必须符合标准?
这绝对可以通过在 asm 中而不是在 C 中编写分配器来解决,但我并不是特别热衷于这样做。如果问题未指定,请告诉我。
【问题讨论】: