Coder
Coder

Reputation: 3715

Binary serialization of variable length data and zero length arrays, is it safe?

I did some research but cannot find a definite approval or disapproval.

What I want is, a fixed size structure + variable length part, so that serialization can be expressed in simple 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 can't find if MSVC, GCC, CLang etc., are ok with it.

Maybe there is a better way to achieve the same?

I really don't want those ugly casts all around:

memcpy((char*)(((char*)buffer)+sizeof(serialize_data)), "abcd", 5);

Upvotes: 3

Views: 969

Answers (1)

ouah
ouah

Reputation: 145899

This program is using a zero length array. This is not C but a GNU extension.

http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

A common idiom in C89, called the struct hack, was to use:

struct serialized_data
{
    int len;
    int type;
    char variable_length_text[1];
}; 

Unfortunately its common use as a flexible array is not strictly conforming.

C99 comes with something similar to perform the same task: a feature called the flexible array member. Here is an example right 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]));

Upvotes: 2

Related Questions