Home > Mobile >  Should I worry about structure alignment in C language when I write applications or it is done autom
Should I worry about structure alignment in C language when I write applications or it is done autom

Time:09-06

I'm trying to understand if structure alignment could affect the programs that I write in C language. It seems that it is something that is handled automatically for us. The question is:

  1. Should I worry about it when writing applications ?
  2. If yes, then when exactly should I worry about it ?

CodePudding user response:

Yes you should care about it since ignoring alignment might produce needlessly memory consuming code.

It's a hard requirement by the standard that struct members are to be allocated so that the first item is at the lowest address. The compiler isn't allowed to re-order them for memory optimization purposes. So if you write a bad struct like this (assuming 32/64 bit CPU):

typedef struct
{
  char a;
  /* 3 bytes padding here */
  int  b;
  char c;
  /* 3 bytes padding here */
} bloat_t;

// total size: 12

Since the CPU in this example has to read b 32 bit aligned, then the compiler has no choice but to insert 3 padding bytes between a and b. In addition to the 3 padding bytes it has to insert at the end no matter. So when I compile this struct on x86 Linux, I get size 12, which is a waste of space.

This can only be fixed by the programmer, who needs to be aware of such alignment requirements:

typedef struct
{
  int  b;
  char a;
  char c;
  /* 2 bytes padding here */
} good_t;

// total size: 8

or alternatively

typedef struct
{
  char a;
  char c;
  /* 2 bytes padding here */
  int  b;
} good_t;

// total size: 8

CodePudding user response:

As other comments/answers have implied, the answer is "it depends."

If you're writing an app for a modern system (meaning ample memory), and your lack of size optimization will only result in the waste of a few K of memory, then no, it probably doesn't matter (though it may not be "best practices").

If, on the other hand, your application may create a huge array of these structures, and/or your struct has enormous inefficiencies, then it might eventually pose a problem.

If your struct is defining a header or a low-level message sequence (commonly found in embedded applications), than it most assuredly will matter, not only because of wasted space, but it can cause operations like memcpy() into the struct not to behave as you might expect. (I realize that such operations also are not "best practices" but they occur all the time in embedded applications, and defensive programming would suggest that you prevent this.) The only remedy for this that I can think of is to define the struct as packed.

  • Related