C memory allocator and strict aliasing -
even after reading quite bit strict-aliasing rules still confused. far have understood this, impossible implement sane memory allocator follows these rules, because malloc can never reuse freed memory, memory used store different types @ each allocation.
clearly cannot right. missing? how implement allocator (or memory pool) follows strict-aliasing?
thanks.
edit: let me clarify question stupid simple example:
// s == 0 frees 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... }
i don't think you're right. strictest of strict aliasing rules count when memory allocated purpose. once allocated block has been released heap free
, there should no references , can given out again malloc
.
and void*
returned malloc
not subject strict aliasing rule since standard explicitly states void pointer can cast other sort of pointer (and again). c99 section 7.20.3 states:
the pointer returned if allocation succeeds suitably aligned may assigned pointer type of object , used access such object or array of such objects in space allocated (until space explicitly deallocated).
in terms of update (the example) don't return memory heap, think confusion arises because allocated object treated specially. if refer 6.5/6
of c99, see:
the effective type of object access stored value declared type of object, if (footnote 75: allocated objects have no declared type).
re-read footnote, it's important.
if value stored object having no declared type through lvalue having type not character type, type of lvalue becomes effective type of object access , subsequent accesses not modify stored value.
if value copied object having no declared type using memcpy or memmove, or copied array of character type, effective type of modified object access , subsequent accesses not modify value effective type of object value copied, if has one.
for other accesses object having no declared type, effective type of object type of lvalue used access.
in other words, allocated block contents become type of data item put in there.
if put float
in there, should access float
(or compatible type). if put in int
, should process int
(or compatible type).
the 1 thing shouldn't put specific type of variable memory , try treat different type - 1 reason being objects allowed have trap representations (which cause undefined behaviour) , these representations may occur due treating same object different types.
so, if store int
in there before deallocation in code, reallocate float
pointer, should not try use float until you've put 1 in there. until point, type of allocated not yet float
.
Comments
Post a Comment