Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: One works, the other doesn't? Date: Thu, 28 Nov 2019 15:54:15 -0800 Organization: A noiseless patient Spider Lines: 62 Message-ID: <86v9r38sm0.fsf@linuxsc.com> References: <0EgwF.8082$kt1.6599@fx46.iad> <87imnvj2v6.fsf@bsb.me.uk> <87y2wrgrr3.fsf@bsb.me.uk> <87v9re7qbi.fsf@bsb.me.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="81b92e3fa8397acac1ab5cf195ff75cd"; logging-data="8012"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/wctrv+yAXKIwBKqTuw2X05DPJjQZpbJA=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:mqTpQOnaxCF57X9VO+w2AHwSueA= sha1:qACIgyDl3FgzebHotIw1RzE2u2o= Xref: csiph.com comp.lang.c:148202 jak writes: > Il 20/11/2019 12:14, Ben Bacarisse ha scritto: > >> jak writes: >> >>> Il 08/11/2019 01:02, Ben Bacarisse ha scritto: >>> >>>> jak writes: >> >> >> >>>>> typedef struct LIST >>>>> { >>>>> char *str; >>>>> int count; >>>>> struct LIST *pMin, *pMaj; >>>>> } Lista; >>>>> >>>>> Lista *BuildList(char *str) >>>>> { >>>>> Lista *lRet = malloc(sizeof(Lista)); >>>>> if(lRet != NULL) >>>>> { >>>>> lRet->str = malloc((strlen(str) + 1) * sizeof(str[0])); >>>> >>>> You could avoid doing two allocation by using a C99 flexible array >>>> member: >>> >>> I know but unfortunately I can't afford to choose which compiler to >>> use and during my work I meet really old compilers, so I tend to >>> ignore the new features. >> >> There's a very old trick to do the same thing: >> >> typedef struct LIST >> { >> int count; >> struct LIST *pMin, *pMaj; >> char str[1]; >> } Lista; >> >> Then you over-allocate the struct and store the string in-place, so to >> speak. Of course it is technically undefined to access elements of the >> str member with indexes > 1, but it was (and is) such a widely-used hack >> that I would be surprised if any compiler did not take the possibility >> into account. >> >> > > I guess I have to declare the string at the end of the struct. [...] You could use the original structure definition, and simply point the 'str' member at the end of the struct (disclaimer: not compiled): size_t extra = strlen( str ) + 1; Lista *p = malloc( sizeof *p + extra ); // check for allocation failure p->str = (char*)p + sizeof *p; No hack required.