D
Darren Cubitt
Hi CLC,
For a while I've been using a pool allocator I wrote for fixed sized
objects. Basically, it allocates chunks of 32 (or however many bits in
an int) objects of a given size, and returns pointers to the individual
objects as required.
One problem I needed to deal with is, when a user calls the free
function, the allocator needs to be able to work out where the object is
with respect to the allocated chunk.
I got around this by allocating an extra int per object. This int stores
the index of this object in the chuck, from which the chuck address can
be calculated. This will give you the general idea:
int * ptr = malloc(sizeof_object + sizeof(int));
ptr[0] = index_of_object;
return ptr + 1;
Thanks to reading this group, I now know this is a Bad Idea(tm) due to
memory alignment issues - something I have been ignorant of in the past.
It seems what I need to do is instead of using sizeof(int) I need to
calculate the "universal alignment" value - for lack of a better name.
Obviously, there must be one or malloc() couldn't work.
So if I create a union of all the intrinsic types, and can then
calculate the alignment for that union, I should be set, right?
In short, would this code be correct and portable:
#include "intrinsic_types.h" /* intrinsic_types_t */
size_t a = offsetof(struct {char a; instrinsic_types_t b;}, b);
Also, is using a struct definition in offsetof() ok? It compiles fine in
MSVC, but that is hardly reassuring.
For a while I've been using a pool allocator I wrote for fixed sized
objects. Basically, it allocates chunks of 32 (or however many bits in
an int) objects of a given size, and returns pointers to the individual
objects as required.
One problem I needed to deal with is, when a user calls the free
function, the allocator needs to be able to work out where the object is
with respect to the allocated chunk.
I got around this by allocating an extra int per object. This int stores
the index of this object in the chuck, from which the chuck address can
be calculated. This will give you the general idea:
int * ptr = malloc(sizeof_object + sizeof(int));
ptr[0] = index_of_object;
return ptr + 1;
Thanks to reading this group, I now know this is a Bad Idea(tm) due to
memory alignment issues - something I have been ignorant of in the past.
It seems what I need to do is instead of using sizeof(int) I need to
calculate the "universal alignment" value - for lack of a better name.
Obviously, there must be one or malloc() couldn't work.
So if I create a union of all the intrinsic types, and can then
calculate the alignment for that union, I should be set, right?
In short, would this code be correct and portable:
#include "intrinsic_types.h" /* intrinsic_types_t */
size_t a = offsetof(struct {char a; instrinsic_types_t b;}, b);
Also, is using a struct definition in offsetof() ok? It compiles fine in
MSVC, but that is hardly reassuring.