Thread: memory boundry alignment with stuctures

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    6

    memory boundry alignment with stuctures

    This is a Linux gcc question.
    When defining a structure, do I have to be
    concerned with how the variables aligned
    themselves in memory? For example, if the,
    if all the data types within the structure added
    up to 32 bytes, would that be more efficient
    then a structure of 33 bytes?
    This used to be an issue ( the 16 byte memory
    boundary used by Intel x86 as segments ) way
    back in the dark ages, but since this is still the
    age of Intel x86 processors, does memory
    alignment in structures matter or no?

  2. #2
    Registered User
    Join Date
    Jan 2006
    Location
    Berkeley, Ca
    Posts
    195
    Yes, memory alignment in C structures still matter. There are various (non-portable) ways to ensure the alignment of the variables in memory will be aligned from one machine to the next. Some methods would be using #pragma or taking the union.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > do I have to be concerned with how the variables aligned themselves in memory?
    No, that's the job of the compiler.

    Because the compiler is free to add padding bytes between members of a structure, the size of a struct from one machine to another can be different.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    If you write/read your structures to/from files in binary mode, alignement does matter. But then endianness matters as well.
    Kurt

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  2. Suggestions on this C style code
    By Joelito in forum C Programming
    Replies: 11
    Last Post: 06-07-2007, 03:22 AM
  3. memory alignment of a struct
    By George2 in forum C Programming
    Replies: 4
    Last Post: 04-04-2007, 12:34 PM
  4. Relate memory allocation in struct->variable
    By Niara in forum C Programming
    Replies: 4
    Last Post: 03-23-2007, 03:06 PM
  5. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 02:15 AM