Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this hack valid according to standard?

Tags:

c

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;

}
like image 357
Nyan Avatar asked Jul 25 '10 14:07

Nyan


1 Answers

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.

like image 73
R.. GitHub STOP HELPING ICE Avatar answered Oct 05 '22 08:10

R.. GitHub STOP HELPING ICE