2

Assume I have a C/C++ struct

struct ABCTYPE
{
  double A;
  double B;
  double C;
};

Is it ensured to have no extra padding on any kind of modern platforms?

To be more specific, if I use

std::vector<ABCTYPE> storage;
// add some elements

// now i need some C routines to the data
double* param=&(storage[0]);
c_routine(param);  // Tested OK on Win/Linux, but will it work on any platforms?
xis
  • 24,330
  • 9
  • 43
  • 59

4 Answers4

4

It is technically possible for such a struct to have padding. Even the simple case of a struct containing only one member can have padding:

C++ sizeof wrapper class

Community
  • 1
  • 1
Thomas Eding
  • 35,312
  • 13
  • 75
  • 106
  • Yes. But I am wondering what will happen if I am using pure double. In my mind double should not pad since it has 8 bytes, 64-bits and have perfect alighment for both 32-bit and 64-bit and even 128-bit systems. – xis May 16 '12 at 18:41
  • It doesn't matter. I, as a compiler writer, could implement C++ where all classes/structs pad structs with useless memory if I wanted to. – Thomas Eding May 16 '12 at 18:46
1

In Visual C++ it is possible to use #pragma pack to change the padding of a structure; the value can be set to more than sizeof(double) which is 8. The documentation shows an example of setting it to 16.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • -1. IMO, while technically correct, this answer is misleading. As pointed out in my answer, if you set the padding to 16, a member of size 8 will still only be aligned to an address that's a multiple of 8. – Jerry Coffin May 16 '12 at 17:27
0

As far as your specific question about std::vector goes, the answer to whether the equivalence you ask about above is valid can be found in this stackoverflow posting.

Community
  • 1
  • 1
FrankH.
  • 17,675
  • 3
  • 44
  • 63
  • No. std::vector is guaranteed to be continuous. However, the struct itself might have padding. – xis May 16 '12 at 17:51
0

In theory it's possible. In reality, I'd be somewhat surprised to see it (though if, for example, you changed the type from double to short, padding would become rather less surprising).

With MS VC, #pragma pack only causes alignment to (at most) the size of the object: From MSDN:

n (optional)

Specifies the value, in bytes, to be used for packing. The default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller. [emphasis added]

This means a struct containing multiple members of the same type will never have padding inserted between them. #pragma pack controls the maximum amount of padding that can be inserted, not the minimum.

Community
  • 1
  • 1
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111