This is just like struct hack. Is it valid according to 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; // is this OK?
f->comment = f + 1 + num;
f->num_foo = num;
...
return f;
}
Yes, it's completely valid. And I would strongly encourage doing this when it allows you to avoid unnecessary additional allocations (and the error handling and memory fragmentation they entail). Others may have different opinions.
By the way, if your data isn't void *
but something you can access directly, it's even easier (and more efficient because it saves space and avoids the extra indirection) to declare your structure as:
struct foo {
size_t num_foo;
type data[];
};
and allocate space for the amount of data you need. The []
syntax is only valid in C99, so for C89-compatibility you should use [1]
instead, but this may waste a few bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With