即使在阅读了很多关于严格别名规则的内容之后,我仍然感到困惑。据我了解,不可能实现遵循这些规则的合理内存分配器,因为 malloc 永远不能重用释放的内存,因为内存可用于在每次分配时存储不同的类型。
显然这是不对的。我错过了什么?您如何实现遵循严格别名的分配器(或内存池)?
谢谢。
编辑:让我用一个愚蠢的简单例子来澄清我的问题:
// s == 0 frees the pool
void *my_custom_allocator(size_t s) {
static void *pool = malloc(1000);
static int in_use = FALSE;
if( in_use || s > 1000 ) return NULL;
if( s == 0 ) {
in_use = FALSE;
return NULL;
}
in_use = TRUE;
return pool;
}
main() {
int *i = my_custom_allocator(sizeof(int));
//use int
my_custom_allocator(0);
float *f = my_custom_allocator(sizeof(float)); //not allowed...
}