Can a structure be less than the sum of its components?

I know that the compiler can add some padding bytes to the structure. But is it possible, when the compiler sees that we never read from a variable inside the structure, that the structure will be smaller 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? } } 
+6
source share
4 answers

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

15 Inside the structure object, members that are not bit fields and the units in which the bit fields are located have addresses that increase in the order in which they are declared. [...] Inside there may be an unnamed complement to the structure object, but not at the beginning.

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

+7
source

No, It is Immpossible. When you take sizeof(foo) , you expect to get at least sizeof(int) + sizeof(intmax_t) . If the compiler gave you a smaller size, this would incorrectly affect the behavior of the program, which is not allowed.

Suppose you put the last element as a "dummy" place holder, to ensure that the reserved hardware register is not used, or to ensure proper alignment. If the compiler removes such an element, it would break the program.

+3
source

If the structure is declared in an automatic or static variable, and neither the structure, nor any part of it has its own address, which was used and in any way understood by the compiler, then the compiler can change the layout of the structure if all the code that uses structure, adjusted accordingly. The important thing is that the code cannot determine whether the compiler can do such a thing except by using mechanisms outside the language (for example, viewing the memory layout using the debugger or accessing areas of memory that have no specific use).

0
source

Absolutely not .

How can any compiler foresee what you are going to write tomorrow? The fact that all current source code does not use this element in no way guarantees that there will never be source code trying to access this part of the structure.

0
source

Source: https://habr.com/ru/post/1012533/


All Articles