Binary serialization of variable length data and zero length arrays, is it safe?
I've done some research but can't find any definite approval or disapproval.
I want it to be a fixed size + variable length structure so that serialization can be expressed in a simpler and less error prone way.
struct serialized_data
{
int len;
int type;
char variable_length_text[0];
};
And then:
serialize_data buff = (serialize_data*)malloc(sizeof(serialize_data)+5);
buff->len=5;
buff->type=1;
memcpy(buff->variable_length_text, "abcd", 5);
Unfortunately, I cannot find if MSVC, GCC, CLang, etc. are supported.
Maybe there is a better way to achieve the same?
I really don't need these ugly casts:
memcpy((char*)(((char*)buffer)+sizeof(serialize_data)), "abcd", 5);
source to share
This program uses a zero-length array. It is not C, but a GNU extension.
http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
A common idiom in C89 called struct hack was to use:
struct serialized_data
{
int len;
int type;
char variable_length_text[1];
};
Unfortunately, its general use as a flexible array is not strictly appropriate.
C99 comes with something similar to doing the same thing: a function called a flexible array member. Here's an example straight from the Standard (C99, 6.7.2.1p17)
struct s { int n; double d[]; };
int m = 12; // some value
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
source to share