After reading this, I have a similar question like this one, wondering how a memory allocator can work without violating the strict aliasing rules. But I am not wondering about re-using freed memory, I wonder about how allocated objects can be positioned within linear memory without violating strict aliasing.
All heap memory allocators I have looked at so far divide their memory in some sort of blocks, with a header in front. However, malloc returns a void *
and usually points to the memory right after the header. Here is an extremely narrowed down example to illustrate this.
#include <stddef.h>
struct block_header {
size_t size;
};
struct block_header *request_space(size_t size);
void *malloc(size_t size) {
struct block_header *block = request_space(size);
// I guess this violates strict aliasing, because the caller will
// convert the pointer to something other than struct block_header?
// Or why wouldn't it?
return block + 1;
}
I have been looking at this for a while now, but I see no way how an allocator could possibly position it's pointers in a memory region without violating strict aliasing. What am I missing?