0

when is simply execute

cout << sizeof(string);

i got 8 as answer.

now i am having a structure

typedef struct {
    int a;
    string str;
} myType;

and i am executing

cout << sizeof(myType);

i got 16 as the answer.

now i made a change in my structure

typedef struct {
    int a, b;
    string str;
} myType;

and i am executing

cout << sizeof(myType);

i got 16 as the answer!!!. How? What is happening?

indiv
  • 17,306
  • 6
  • 61
  • 82
Venkatesh
  • 1,537
  • 15
  • 28
  • The compiler configuration at ideone.com (http://ideone.com/6LYvXN) yields 12 as the size of the struct. – Steve Guidi Nov 13 '14 at 21:14
  • 2
    Please do NOT do typedef struct { ... } typename; That is C. While it is allowed in C++ for backward compatibility, it is not idiomatic. It's downright annoying. Use struct typename { ... }; – Rob K Nov 13 '14 at 21:29
  • 1
    Thanks @Rob K I will keep this in mind and I wont repeat this again – Venkatesh Nov 13 '14 at 21:33

4 Answers4

7

Perhaps padding is happening. E.g. sizeof(int) can be 4 bytes and compiler can add 4 bytes after a for the sake of data alignment. The layout could be like this:

typedef struct {
    int a;      // 4 bytes
                // 4 bytes for padding
    string str; // 8 bytes
} myType;

typedef struct {
    int a;      // 4 bytes
    int b;      // 4 bytes
    string str; // 8 bytes
} myType;
AlexD
  • 32,156
  • 3
  • 71
  • 65
0

Looks like 8 byte alignment.

So if you have any data type that has less than 8 bytes, it will still use 8 bytes.

I assume the pointer is 8 byte, whereas the ints are only 4 bytes each.

You can force 1 byte alignment using code like outlined here Struct one-byte alignment conflicted with alignment requirement of the architecture? . You should then get different size for first case.

Community
  • 1
  • 1
Andreas Reiff
  • 7,961
  • 10
  • 50
  • 104
  • 1
    "So if you have any data type that has less than 8 bytes, it will still use 8 bytes" that's not quite true. `std::string` is aligned to 8 bytes in this case, so not any data will use 8 bytes, it depends what comes after that data. – Slava Nov 13 '14 at 21:25
  • Yes, in this case. I assume that std::string is 8 bytes here since it is a (64 bit) pointer and also 8 byte aligned?! – Andreas Reiff Nov 14 '14 at 08:16
0

It's called structure packing to achieve optimal memory alignment.

See The Lost Art of C Structure Packing to understand the how and why. It's done the same way in both C and C++.

Rob K
  • 8,757
  • 2
  • 32
  • 36
-2

In C/C++ structs are "packed" in byte chunks. You can specify which size your structs should be packed. Here a reference: http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx

cabbi
  • 393
  • 2
  • 12