Frankly, is such a code valid or does it produce UB?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct __attribute__((__packed__)) weird_struct
{
int some;
unsigned char value[1];
};
int main(void)
{
unsigned char text[] = "Allie has a cat";
struct weird_struct *ws =
malloc(sizeof(struct weird_struct) + sizeof(text) - 1);
ws->some = 5;
strcpy(ws->value, text);
printf("some = %d, value = %s\n", ws->some, ws->value);
free(ws);
return 0;
}
I’d never think it is valid to something like this, but it would seem that SystemV message queues do exactly that: see the man page.
So, if SysV msg queues can do that, perhaps I can do this too? I think I’d find this useful to send data over the network (hence the __attribute__((__packed__))
).
Or, perhaps this is a specific guarantee of SysV msg queues and I shouldn’t do something like that elsewhere? Or, perhaps this technique can be employed, only I do it wrongly? I figured out I’d better ask.
This - 1
in malloc(sizeof(struct weird_struct) + sizeof(text) - 1)
is because I take into account that one byte is allocated anyway thanks to unsigned char value[1]
so I can subtract it from sizeof(text)
.