To stir up some discussion... wouldn't the following be an acceptable implementation of the same?
Assume that I know that my widget is a small one, maybe small enough to even fit inside a the minimum alignment. Lets say it is a C struct with a few integers in it, something like this:
struct widget
{
uint8_t x;
uint8_t y;
};
It would then be easiest to simply make the widget like this:
typedef union
{
size_t size;
struct widget
{
/* members */
};
} Widget_t;
size_t size = n * sizeof(Widget_t);
Widget_t *ps = (Widget_t*) malloc(size);
ps->size = n;
pw = (Widget_t*) ++ps;
The above code relies solely on "struct padding" (or union padding if you will), ie the padding is decided automatically by the compiler based on the alignment requirements, and appended to the end of the struct/union. This padding is something we can be sure is present on every system, if the system requires memory alignment.
With this method we don't have to worry about pointer casts nor to find the maximum alignment of the system manually: the code becomes easier to read. The only drawback with the above is if the widgets are large. It will then be a waste of memory to store only the size in one such a large memory area.
Thoughts?
