c - What precautions should I take to make a memory pool that does not invoke undefined behavior? -


my initial problem have, on project, several objects share lifetime (i.e., once free 1 of them, i'll free them all), wanted allocate single block of memory. have arrays of 3 different object types, struct foo, void *, , char. @ first wanted malloc() block this:

// +---------------+---------+-----------+---------+---------+ // | struct foo[n] | padding | void *[m] | padding | char[o] | // +---------------+---------+-----------+---------+---------+ 

but then... how accomplish without invoking undefined behavior? i.e., respecting type aliasing rules, aligment... how calculate memory block size, declare memory block (with effective type), , how pointers 3 sections within portably?

(i understand malloc() 3 blocks, result in 3 free(), i'd know how single block while still well-behaved.)

i'd extend problem more general question: precautions should 1 take implement memory pool objects arbitrary sizes , alignment while keeping program well-behaved? (assuming possible implement without invoking undefined behavior.)

however hard try, it's not possible implement malloc in pure c.

you end violating strict aliasing @ point. avoidance of doubt, using char buffer doesn't have dynamic storage duration violate strict aliasing rules. have make sure pointer returned has appropriate alignment.

if you're happy tie down particular platform may turn particular implementation of malloc inspiration.

but why not consider writing stub function calls malloc , builds table of other allocated objects? implement kind of observer / notify framework. starting point well-known garbage collectors have been written in c.


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -