Re: OT: Language War (Re: "C" Manual)
On Sat, 5 Jan 2002, Eric G.Miller wrote:
> is one of the reasons pointers to char are so common. However, there
> is a little trick that's guaranteed to always work:
>
> struct foo {
> size_t length;
> char str[1];
> };
>
> ...
>
> struct foo * str_to_foo(char *a)
> {
> size_t len = strlen (a);
> struct foo *bar = malloc (sizeof(struct foo) + len);
> if (bar) {
> bar->length = len;
> memcpy (bar->str, a, len); /* bar->str now not NUL terminated */
> }
> return bar;
> }
It doesn't look particularly guaranteed to me. You're really allocating
*three* pieces of memory here - one for the struct foo, one for the
1-character array chr, and one for the rest of the string. Your example
assumes that chr will be located in memory immediately after foo - which
it probably will, but it might not. It could be anywhere, the language
makes no guarantee. The compiler might even choose to put the 1-char
array before foo, so you can't use it without overwriting your struct
Structs have fields. Use them.
> The benefit is being able to use one malloc vs. two (for any similarly
This is a benefit why? :}
Reply to: