Thread: Struct packing and logistics

  1. #1
    Registered /usr
    Join Date
    Aug 2001
    Location
    Newport, South Wales, UK
    Posts
    1,273

    Question Struct packing and logistics

    Hi,

    I making a small C program that creates different objects in a window dependant on the data in an external file (A scripting system, if you like).
    I made three structs, which have a parent-child relationship (one struct has a pointer to an array of the second struct which has a pointer to an array of the third struct >puff< >pant< ). They are also stored in this way in the file.

    After reading the first struct, allocating space for all of its child structs and reading them, I then come to allocating space for all the children of each of the 2nd structs, and reading them. The only thing is, reading the data directly from the disk into the whole struct seems to leave a byte of data out.
    This doesn't happen, however, when each data is read into each individual member of the struct. Asking around produced the response "the struct is being packed to alignment in memory", and checking the Project Settings in MSVC shows an 8-byte boundary alignment. Struct 1 is 10 bytes long (hmm), struct 2 is 16 bytes long (no problems there) and struct 3 is 19 bytes long (ahh... )!

    The question is, do I adjust the alignment to smaller boundaries ("degrading performance" as MSDN puts it), or add empty bytes to my files to retain alignment?

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Can you show some code please... and maybe someone can advise you better. Specifically the section doing the open, read and write.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >The question is, do I adjust the alignment to smaller boundaries
    >("degrading performance" as MSDN puts it), or add empty bytes
    >to my files to retain alignment?
    How portable do you want this program to be? If the answer is (correctly) "very", then you might as well assign the values member by member instead of reading the whole struct. Since by reading the whole struct directly I assume that you are using fread, which is not generally portable to begin with. If you don't mind a non-portable program then you could use bitfields in the struct to force alignment.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed