Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a struct be smaller than the sum of its components?

Tags:

c

struct

sizeof

I know that the compiler may add some padding bytes in a struct. But is it possible, when the compiler sees that we never read from a variable inside a struct, that the struct will have a smaller size than the total size of the members?

struct Foo_T
{
  int a;
  intmax_t b;
};


void bar(void)
{
  struct Foo_T foo;
  foo.a=rand();
  someFunction(foo.a);
  //i never access foo.b, only foo.a
  if(sizeof(foo)< sizeof(int)+sizeof(intmax_t))
    {
      //is it possible that we can end here?
    }
}
like image 620
12431234123412341234123 Avatar asked Nov 21 '16 14:11

12431234123412341234123


2 Answers

No, this is prohibited by the C standard. In C11, section 6.7.2.1 contains this statement:

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. [... ] There may be unnamed padding within a structure object, but not at its beginning.

Removing members of a struct would violate the requirement that the members have addresses that increase in the order in which they are declared.

like image 195
Sam Holloway Avatar answered Oct 19 '22 22:10

Sam Holloway


No it isn't possible. When you take sizeof(foo) you expect to get at least sizeof(int) + sizeof(intmax_t). If the compiler would have given you a lesser size, it would have incorrectly affected the behavior of the program, which isn't allowed.

Suppose that you put the last member there as a place-holder "dummy", to guarantee that a reserved hardware register isn't used, or to ensure correct alignment. If the compiler would remove such a member, it would have broken the program.

like image 45
Lundin Avatar answered Oct 19 '22 23:10

Lundin