Is this how one can use the the \"extra\" memory allocated while using the C struct hack?
Questions:
I have a C struct hack implementation below. My questio
I would advise against that due to possible alignment issues instead consider this:
struct my_struct
{
char *arr_space;
unsigned int len;
}
struct my_struct *ptr = malloc(sizeof(struct my_struct) + 10);
ptr->arr_space = ptr + 1;
ptr->len = 10;
This will give you locality as well as safety :) and avoid weird alignment issues.
By alignment issues I meant possible access delays for accessing unaligned memory.
In the original example if you add a byte or non word aligned member (byte, char, short) then the compiler may extend the size of the structure but as far as your pointer is concerned you are reading the memory directly after the end of the struct (non aligned). This means if you have an array of an aligned type such as int
every access will net you a performance hit on CPUs that take hits from reading unaligned memory.
struct
{
byte_size data;
char *var_len;
some_align added by compiler;
}
In the original case you will be reading from the some_align
region which is just filler but in my case you will read from aligned extra memory afterwards (which wastes some space but that's typically okay).
Another benefit of doing this is that it's possible to get more locality from allocations by allocating all the space for variable length members of a struct
in one allocation rather than allocating them separately (avoids multiple allocation call overheads and gives you some cache locality rather than bouncing all over memory).