Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the sizeof() value determined by compiler or linker?

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.

like image 895
Dan Avatar asked Feb 17 '23 02:02

Dan


1 Answers

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.

like image 130
John Dibling Avatar answered Feb 25 '23 02:02

John Dibling