Path: csiph.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: Nice way of allocating flexible struct. Date: Sun, 14 Dec 2025 22:48:42 -0800 Organization: A noiseless patient Spider Lines: 26 Message-ID: <86jyyouto5.fsf@linuxsc.com> References: <20251007233002.852@kylheku.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Date: Mon, 15 Dec 2025 06:48:45 +0000 (UTC) Injection-Info: dont-email.me; posting-host="3b66f75cc16331490dd39d06d7ef9603"; logging-data="1779032"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/1jGrOhmxAGVtpdFWBHstRt5AUR5+SA6o=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:kOno79WI1wzBS0MIWgb5hqMDAPw= sha1:krfUOyHWpAEZfL1YCcrg/CAPuw4= Xref: csiph.com comp.lang.c:395810 Kaz Kylheku <643-408-1753@kylheku.com> writes: > Jonas Lund of https://whizzter.woorlic.org/ mentioned this > trick in a HackerNews comment: > > Given: > > struct S { > // ... > T A[]; > }; > > Don't do this: > > malloc(offsetof(S, A) + n * sizeof (T)); > > But rather this: > > malloc(offsetof(S, A[n])); > > It's easy to forget that the second argument of offsetof is a > designator, not simply a member name. Clever but inadvisable. Even if the offsetof() expression compiles, in most cases it either gives a value that is too small or is undefined behavior.