2

Look at these 2 structs

struct parent_t
{
    short num1;
    char chrA;
    char chrB;
    char chr1;
};

struct child_t
{
    struct parent_t parent;
    char chr2;
};

As we know, padding maybe added to struct members in order to increase it to a comfortable RAM-friendly size. In parent_t's case, chr1 will likely be padded because of its minusculity. Whilst chrA and chrB will likely be combined and share the same word in ram.

Now if we look at child_t, it has chr2, which by itself would be padded. My question is will chr1 and chr2 be optomise such as chrA and chrB? If so, what is that called?

For this instance I am assuming that a 1 word = 1 short = 2 chars.

Dellowar
  • 3,160
  • 1
  • 18
  • 37
  • 3
    I suspect that the answer to your question is compiler specific. different compilers might pad and align in a different way. you can try to dump the memory (using the address and sizeof()) and check. – eyalm Dec 01 '16 at 22:23
  • 1
    duplicate of http://stackoverflow.com/questions/4306186/structure-padding-and-packing – John Dec 01 '16 at 22:23
  • actually, you would use `offsetof` macro (which isn't standard on all environments, but it's simple enough to lookup/implement). And yes, this definitely does change based on which compiler you're using. – John Dec 01 '16 at 22:26
  • Too broad. Depends on architecture, ABI. Also sounds like an XY problem. **Why** do you care? Don't rely on a specific memory layout for any type of object. – too honest for this site Dec 01 '16 at 22:37

1 Answers1

1

My question is will chr1 and chr2 be optomise such as chrA and chrB?

No, they will not be optimized in the way you describe.

The reason is that sizeof(struct parent_t) must be the same everywhere in the program.

If it was optimized this code would fail:

struct parent_t p;
struct child_t c;
//... initialize p
memcpy(&c.parent, &p, sizeof(struct parent_t));

Such code is valid and must work. In other words - the optimization you describe will not happen.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • For completeness, some compilers do reorder fields of structs when they can prove that all references to struct are local to current translation unit. But this is quite rare and AFAIR not available neither in GCC, nor in LLVM. – yugr Dec 04 '16 at 06:46