c - Is this hack valid according to standard? -
this struct hack. valid according standard c?
// error check omitted! typedef struct foo { void *data; char *comment; size_t num_foo; }foo; foo *new_foo(size_t num, blah blah) { foo *f; f = malloc(num + sizeof(foo) + max_comment_size ); f->data = f + 1; // ok? f->comment = f + 1 + num; f->num_foo = num; ... return f; }
yes, it's valid. , encourage doing when allows avoid unnecessary additional allocations (and error handling , memory fragmentation entail). others may have different opinions.
by way, if data isn't void *
can access directly, it's easier (and more efficient because saves space , avoids indirection) declare structure as:
struct foo { size_t num_foo; type data[]; };
and allocate space amount of data need. []
syntax valid in c99, c89-compatibility should use [1]
instead, may waste few bytes.
Comments
Post a Comment