Is it conforming with the standard to pack two objects using the align of the second object to get the final size?
I'm using this approach for a doubly linked list, but extracting the relevant part:
#include <stdio.h>
#include <stdlib.h>
#include <stdalign.h>
struct node
{
struct node *prev;
struct node *next;
};
#define get_node(data, szof) ((struct node *)(((char *)data) + szof))
int main(void)
{
size_t align = alignof(struct node);
double *data;
// Round size up to nearest multiple of alignof(struct node)
size_t szof = (sizeof(*data) + (align - 1)) / align * align;
// Pack `data` + `struct node`
data = malloc(szof + sizeof(struct node));
// Get node using a generic pointer to calculate the offset
struct node *node = get_node(data, szof);
*data = 3.14;
node->prev = NULL;
node->next = NULL;
printf("%f\n", *data);
free(data);
return 0;
}
Where data
can be a pointer to any primitive or composite type.