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

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -