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?
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With