home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!usc!sdd.hp.com!swrinde!gatech!concert!sas!mozart.unx.sas.com!sasghm
- From: sasghm@theseus.unx.sas.com (Gary Merrill)
- Newsgroups: comp.lang.c
- Subject: Re: Memory alignment of struct elements
- Message-ID: <BsxCtz.598@unx.sas.com>
- Date: 13 Aug 92 13:44:23 GMT
- References: <1992Aug12.133132.10723@Princeton.EDU>
- Sender: news@unx.sas.com (Noter of Newsworthy Events)
- Organization: SAS Institute Inc.
- Lines: 44
- Originator: sasghm@theseus.unx.sas.com
- Nntp-Posting-Host: theseus.unx.sas.com
-
-
- In article <1992Aug12.133132.10723@Princeton.EDU>, udalski@astro.Princeton.EDU (Andrzej Udalski) writes:
- |> I am writing the software for a big database and the space is very
- |> important. If I try to use a
- |>
- |> struct { char ch ; float f }
- |>
- |> the compiler (both in SunOS 4.0.1 and Interactive SYSVR3) allocates
- |> 8 bytes for it, starting the "f" element at fifth byte of the structure.
- |> This makes both reading and writing such records from/to a binary database
- |> file (consisting of 5-byte-long records) very inconvinient, requiring
- |> a declaration of character array of 5 bytes and using "memcpy()". Is there
- |> a way to force the compiler to align the struct elements following their
- |> true length?
-
- This depends upon the compiler, of course. Many compilers have such
- an option, but (depending upon the architecture, etc.) it may not
- be a good idea to use it. You might simply try:
-
- struct { float f; char ch; }
-
- which will not require the internal padding you are encountering.
- In general, to avoid such padding you should define your structure
- members in decreasing order of alignment requirements. Note that
- the compiler will tend to add padding to the *end* of the structure
- in order to achieve correct alignment in *arrays* of such structures.
- Still, such an approach may help you.
-
- I would be a little concerned about the maintainability of your code,
- however. If things are done in a careful and modular manner (and,
- for example, sizes of records, etc. are not "hardcoded"), I do not
- see much inconvenience in going to/from the database via an intermediate
- buffer. The danger you need to be aware of, of course, is the
- possibility that in the future someone decides to add a new field to
- your structure, and either adds it in the "wrong" place (for padding
- purposes) or forgets to update routines that access it. Whatever you
- do, you should choose safety and maintainability over any small
- gain in what might be thought of as "convenience".
-
-
- --
- Gary H. Merrill [Principal Systems Developer, C Compiler Development]
- SAS Institute Inc. / SAS Campus Dr. / Cary, NC 27513 / (919) 677-8000
- sasghm@theseus.unx.sas.com ... !mcnc!sas!sasghm
-