I'm trying to troubleshoot a c++ problem where two parts of my code are returning different results for the sizeof() operator.
Here's what I run
MyClass* foo = new MyClass();
int size = sizeof(*foo)
I place this code in two different sections of my project and I get two different results. One time it 2254, another is 2284. I can look at the memory layout and one area shows the internal members as byte-aligned, another area it's word aligned.
I look at the dissasmbly and see that the sizeof() values are actually part of the machine code. Would this be a bug in the compiler or the linker? Why would two parts of the same project view the same class differently?
EDIT:
Let me provide a more clear example that I just ran to show that this is NOT a ODR violation.
I just made a brand new class as such
class TestAlignClass
{
public:
TestAlignClass() { }
~TestAlignClass() { }
private:
char charArray[3];
int myInt;
};
If the class is aligned to 4, it should return sizeof() = 8 which is what I want. But there are certain classes in my code that return sizeof() = 7.
In fact when I step into the new() operator, sometimes it allocates 7 bytes and sometimes it allocate 8.
I am linking several projects together and I thought it had to do with project settings at first, but different parts of the same project will show the discrepancy.
sizeof
is evaluated at compile time.
As for why sizeof
returns different values for the same construct in two different places, the classes must be defined differently somehow in the different translation units.
One place I would look first is the packing. If there is a #pragma pack (1)
type expression in one TU but not in another, that could account for the difference. It could also indicate a violation of the One Definition Rule, but that's another story.
Another, perhaps more exotic thing to look for is the presence of #ifdef
type macros which effect what is part of the class.
As @MooingDuck rightly observes in the comments, it is extremely likely that the bug is in your code. Do not assume the compiler is defective.
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