Is the value of sizeof () defined by the compiler or linker?

I am trying to fix a C ++ problem where two parts of my code return different results for the sizeof () operator.

Here i run

MyClass* foo = new MyClass(); int size = sizeof(*foo) 

I place this code in two different sections of my project, and get two different results. One time it is 2254, the other - 2284. I can look at the memory layout, and one area displays the internal elements as byte aligned, the other area that it is aligned.

I look at dissasmbly and see that the sizeof () values ​​are actually part of the machine code. Will this be a bug in the compiler or linker? Why do two parts of the same project view the same class differently?

EDIT:

Let me introduce a clearer example, which I just showed that this is NOT a violation of ODR.

I just created a whole new class as such

 class TestAlignClass { public: TestAlignClass() { } ~TestAlignClass() { } private: char charArray[3]; int myInt; }; 

If the class is aligned by 4, it should return sizeof () = 8, which is what I want. But in my code there are certain classes that return sizeof () = 7.

In fact, when I enter a new () operator, sometimes it allocates 7 bytes and sometimes allocates 8.

I link several projects together, and I thought that this was due to the project settings at first, but different parts of the same project will show a mismatch.

+4
source share
1 answer

sizeof is evaluated at compile time.

As for why sizeof returns different values ​​for the same construct in two different places, classes should be defined differently in different translation units.

One place I would look is packaging. If one TU has an expression like #pragma pack (1) but not another, this might explain the difference. It may also indicate a violation of the Unified Definition rule, but this is a different story.

Another, perhaps more exotic to search for is the presence of #ifdef macros, which affect what is part of the class.

As @MooingDuck notes in the comments, it is very likely that there is an error in your code. Do not assume that the compiler is faulty.

+8
source

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


All Articles