How is memory alignment done usually? [duplicate] - c++

This question already has an answer here:
Size of class with virtual function
(1 answer)
Closed 8 years ago.
Have a look at these 2 cases:
class A {
public:
int a;
A () { a = 10;}
void foo () {std::cout << "a = " << a << std::endl;}
};
Here sizeof(A) gives 4 bytes, which makes sense.
class A {
public:
int a;
A () { a = 10;}
virtual void foo () {std::cout << "a = " << a << std::endl;}
};
Here sizeof(A) gives 16 bytes as opposed to 12 bytes (4 + 8 for pointer).
Is there any explanation in terms of memory alignment for this ?

It's up to the compiler how virtual functions are implemented, but what's likely happening here is it wants/needs to align the 8-byte pointer to the virtual dispatch table on a multiple-of-8 memory address. Then there's either { 4 bytes a, 4 padding, 8 vdt pointer } or { 8 vdt pointer, 4 bytes a, 4 padding } - the latter's less obvious, but consider that arrays of A need to be contiguous and spaced per sizeof(A), so 12's rounded up to 16 given the 8-byte alignment.

FIRST in virtual dispatch table, visual functions need a pointer size , in 32 bits computer, the size of pointer is 4 bytes, int 64 bits it's 8 bytes. so I think your computer is 64 bits.
SECOND the sizeof(A) should consider the padding and memory alignment .
so 16 bytes is arranged like that: 4 bytes(int a) + 8 bytes(a virtual function pointer int 64 bits) + 4 bytes padding(because the max size of elements in A is the virtual function pointer which is 8 bytes, so the sizeof(A)should be the integral multiples of 8 bytes )

Related

C++ - object padding intricacies

I'm trying to understand struct and class padding in depth, so I devised an example I considered more challenging than many of the examples I found in tutorials on the topic. I compiled it in an x64 machine with g++, without enabling any code optimization. My code is as follows:
class Example
{
private:
long double foobar; // 10 bytes + 6 padded bytes as double follows
double barfoo; // 8 bytes + 8 padded bytes
static float barbar; // didn't count as it's a static member
float *fooputs; // 8 bytes + 8 padded bytes
int footsa; // 4 bytes, stored in the padded portion of float
char foo; // 1 byte, stored in the padded portion of float
public:
int function1(int foo) { return 1; }
void function2(int bar) { foobar = bar; }
};
int main()
{
std::cout << sizeof(Example) << std::endl; // 48 bytes
return 0;
}
Although I see that the size of Example is 48 bytes, I expected it to be 37 bytes. The argumentation on my expectation is as follows:
foobar needs 10 bytes. As double follows, 6 more bytes are needed for padding.
barfoo needs 8 bytes, as it's a double. No need for padding, as mod(16,8) == 0
*fooputs needs 8 bytes, as it's a pointer in an x64 architecture. No need for padding, as mod(24,8) == 0
footsa needs 4 bytes as an int. No need for padding, as mod(32,4) == 0
foo needs 1 byte as a char. No need for padding.
As the result is different that the expected, I tried to understand how C++ evaluated the size of Example to 48 bytes by commenting in and out class members. So, besides of the argumentation for foobar I assumed the justifications I'm writing in my inline comments for each member.
Could anyone explain me how the size is evaluated to 48 bytes and if my justifications are correct?
You forget about the final padding. sizeof returns a number of bytes between two adjacent members in an array. In your case, alignof(long double) is very likely 16, therefore each Example instance requires to be at 16-byte aligned address.
Consequently, if you have first instance of Example at a 16-bytes aligned address A, and then there are 37 bytes required by members, the next Example instance cannot be stored at A + 37 bytes, but it needs to be stored at A + k * 16. The smallest possible k that satisfies k * 16 >= 37 is 3. Which finally gives you the number of bytes between two Example instances in an array 3 * 16 = 48, which is exactly sizeof(Example).

Why object with vptr is 12 bytes longer?

#include <iostream>
class B
{
public:
virtual void f() {std::cout<<"HI";}
int x;
};
class A
{
public:
void f() {std::cout<<"HI";}
int x;
};
int main () {
A a;
B b;
std::cout<<sizeof(a)<<" "<<sizeof(b);
return 0;
}
The output is
4 16
I expected it to be 8 bytes longer - vptr pointer. But for what the rest 4 bytes is used?
I found quite many forum posts (all from some years ago) where people discussed that object from the class with vprt is 4 or 8 bytes longer. I checked also on online C++ shell - output there is the same.
It seems that the pointer to the table of pointers to virtual functions has a size of 8 bytes. So the class B is aligned to the boundary of 8 bytes that is it has 4 additional padding bytes.

Class Alignment issue

I was testing a class alignment and found strange behavior. I tested it with VS2012 compiler setting 4 and 8 bytes alignment setting but in each case output is same.
class Alignemnt{
public:
Alignemnt():a(){}
int a;
};
class Alignemnt_1{
public:
int a;
char array[2];
};
class Alignemnt_2{
public:
int a;
char array[2];
int x;
};
std::cout << "Sizeof(Alignemnt) :" <<sizeof(Alignemnt) << std::endl;
std::cout << "Sizeof(Alignemnt_1) :" <<sizeof(Alignemnt_1) << std::endl;
std::cout << "Sizeof(Alignemnt_2) :" <<sizeof(Alignemnt_2) << std::endl;
Every time output is:
Sizeof(Alignemnt) : 4
Sizeof(Alignemnt_1) : 8
Sizeof(Alignemnt_2) : 12
I think, Alignemnt_2 size should be 16 byte.
I assume you are referring to the /Zp switch, which lets you control maximum struct member alignment:
When you specify this option, each structure member after the first is stored on either the size of the member type or n-byte boundaries (where n is 1, 2, 4, 8, or 16), whichever is smaller.
Since you are not using a struct member with an alignment of more than 4 bytes (sizeof(int) and alignof(int) is both 4), all settings of 4 bytes and above will lead to exactly the same behavior.
If you want to specify the exact alignment of a structure member, consider using the standard C++ alignas which allows you to specify the exact alignment a member is supposed to have (VS 2012 should support it iirc).
See the result of using alignas.
Alignment shouldn't change the size of your object, just the starting address of the objects. For instance, an 8 byte aligned object could be at address 0x100000 or 0x100008, or really any address ending in 0 or 8 when written in hex but not 0x100004.
No.
Aligment 2 is fine.
You have 2 chars next to each other, that means you have 2 out of 4 bytes used. The packing will align it to 4 bytes, and then you will end up with 4 + 4 +4 .
If you want to end up to 16 you can try the following declaration :
{
char a;
int b;
char c;
int d;
}

C++ Polymorphic memory cost

I have this chunk of code:
#include <stdio.h>
class CoolClass {
public:
virtual void set(int x){x_ = x;};
virtual int get(){return x_;};
private:
int x_;
};
class PlainOldClass {
public:
void set(int x) {x_ = x;};
int get(){return x_;}
private:
int x_;
};
int main(void) {
printf("CoolClass size: %ld\n", sizeof(CoolClass));
printf("PlainOldClass size: %ld\n", sizeof(PlainOldClass));
return 0;
}
I'm getting a little bit confused because it says that the size of CoolClass is 16? How? Why? Even with the pointer to the vtable, shouldn't the size be 8? Size of oldclass is 4 as expected.
edit: I'm running Linux Mint 64 bit with g++ 4.6.3.
You can't assume anything about the sizes of anything other than char or unsigned char. If you're building on a 64 bit platform, int is likely still 4 bytes, but the size of the virtual table pointer would likely be 8, and the extra 4 bytes are for padding (so that the pointer is aligned to 8 bytes).
64-bit
+----+----+----+----+
| vp | vp | x_ | p |
+----+----+----+----+
vp - virtual table pointer
x_ - member
p - padding byte
32-bit
+----+----+
| vp | x_ |
+----+----+
vp - virtual table pointer
x_ - member
p - padding byte
Padding not required because the pointer is already aligned
As a test, you can try
class PlainOldClass {
private:
int* x_;
};
and its size would be 8.
My best guess is that you're compiling for a platform with 64-bit pointers. Then you'll need 8 bytes for the virtual pointer, probably 4 bytes for the int (some 64-bit platforms will also give that 8 bytes - but you say that sizeof (PlainOldClass) is 4, so that doesn't apply here), and another 4 to give the class the 64-bit alignment required by the pointer - giving a total of 16 bytes.
I think the cost is:
platform with 64-bit pointers, so 8 bytes for the virtual pointer
4 bytes for the int (but might be also 8 bytes on some platforms)
4 to give the class the 64-bit alignment required by the pointer
sum=16 bytes.
It's because your system may be 64-bit system, due to which it becomes,
8 bytes for vptr.
4 bytes for int
and additional 4 bytes padding to give 64-bit alignment to the pointer.
hence sum becomes 16.

C++ sizeof with bool

It is a simple question. Code first.
struct A {
int x;
};
struct B {
bool y;
};
struct C {
int x;
bool y;
};
In main function, I call
cout << " bool : " << sizeof(bool) <<
"\n int : " << sizeof(int) <<
"\n class A : " << sizeof(A) <<
"\n class B : " << sizeof(B) <<
"\n class C : " << sizeof(C) << "\n";
And the result is
bool : 1
int : 4
class A : 4
class B : 1
class C : 8
Why is the size of class C 8 instead of 5?
Note that this is compiled with gcc in MINGW 4.7 / Windows 7 / 32 bit machine.
The alignment of an aggregate is that of its strictest member (the member with the largest alignment requirement). In other words the size of the structure is a multiple of the alignment of its strictest (with the largest alignment requirement) member.
struct D
{
bool a;
// will be padded with char[7]
double b; // the largest alignment requirement (8 bytes in my environment)
};
The size of the structure above will be 16 bytes because 16 is a multiple of 8. In your example the strictest type is int aligning to 4 bytes. That's why the structure is padded to have 8 bytes. I'll give you another example:
struct E
{
int a;
// padded with char[4]
double b;
};
The size of the structure above is 16. 16 is multiple of 8 (alignment of double in my environment).
I wrote a blog post about memory alignment for more detailed explanation
http://evpo.wordpress.com/2014/01/25/memory-alignment-of-structures-and-classes-in-c-2/
Aligning structures to the size of a word, which is 4 bytes here.
Looking at the definition of your struct, you have 1 byte value followed by 4 byte Integer. This integer needs to be allocated on 4 byte boundary, which will force compiler to insert a 3 byte padding after your 1 byte bool. Which makes the size of struct to 8 byte. To avoid this you can change order of elements in the struct.
Also for two sizeof calls returning different values, are you sure you do not have a typo here and you are not taking size of pointer or different type or some integer variable.
Answered by Rohit J on struct size is different from typedef version?