On Tue, Oct 08, 2024 at 01:15:54PM +0000, Taylor R Campbell wrote: > > Date: Tue, 8 Oct 2024 10:06:39 +0200 > > From: tlaro...@kergis.com > > > > In the style file, for structures, the emphasis is put on alignment in > > order to not waste memory because of undue padding. > > > > Shouldn't an exception been mentionned concerning structures that may be > > derived from a base structure, so that the first member of the derived > > structures is a base structure, using the C standard guaranteed property > > that the address of the first member is the address of the structure, > > allowing to cast pointers in order to operate whether on the base > > structure or on the derived structure? > > Don't do that. Use container_of instead. > > struct derived { > struct base b; > int x; > ... > }; > > int > foo(struct base *bptr) > { > struct derived *dptr = container_of(bptr, struct derived, b); > > return dptr->x; > } > > void > bar(struct derived *dptr) > { > struct base *bptr = &dptr->b; > > mumble(bptr, &foo); > } > > This way of writing things is independent of where the base structure > goes. Of course, if there's layers of abstraction involved, it may > not be obvious -- and may not be stable across code evolution -- what > the optimally aligned member ordering is, so putting the base at the > beginning is fine.
Well, I found the definition of container_of in the following headers: ./crypto/dist/ipsec-tools/src/racoon/schedule.h ./external/mit/libuv/dist/src/uv-common.h ./external/mit/libuv/dist/test/task.h ./sys/dev/pci/cxgb/cxgb_adapter.h ./sys/external/bsd/drm2/dist/drm/i915/i915_utils.h ./sys/external/bsd/drm2/dist/drm/nouveau/include/nvif/list.h So it is not a general thing. While placing the shared structure at the beginning is guaranteed to yield the correct result in C (and for the base structure, one can apply size considerations about the order of the members). But, whatever way, it seems to me it is worth a mention at least in style ;-) -- Thierry Laronde <tlaronde +AT+ kergis +dot+ com> http://www.kergis.com/ http://kertex.kergis.com/ Key fingerprint = 0FF7 E906 FBAF FE95 FD89 250D 52B1 AE95 6006 F40C