Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Struct memory layout equivalency

Consider the following C struct and C++ struct declarations:

extern "C" { // if this matters
typedef struct Rect1 {
  int x, y;
  int w, h;
} Rect1;
}

struct Vector {
  int x;
  int y;
}

struct Rect2 {
  Vector pos;
  Vector size;
}
  • Are the memory layouts of Rect1 and Rect2 objects always identical?

  • Specifically, can I safely reinterpret_cast from Rect2* to Rect1* and assume that all four int values in the Rect2 object are matched one on one to the four ints in Rect1?

  • Does it make a difference if I change Rect2 to a non-POD type, e.g. by adding a constructor?

like image 325
emlai Avatar asked Aug 08 '26 21:08

emlai


1 Answers

  • I would think so, but I also think there could (legally) be padding between Rect2::pos and Rect2::size. So to make sure, I would add compiler-specific attributes to "pack" the fields, thereby guaranteeing all the ints are adjacent and compact. This is less about C vs. C++ and more about the fact that you are likely using two "different" compilers when compiling in the two languages, even if those compilers come from a single vendor.
  • Using reinterpret_cast to convert a pointer to one type to a pointer to another, you are likely to violate "strict aliasing" rules. Assuming you do dereference the pointer afterward, which you would in this case.
  • Adding a constructor will not change the layout (though it will make the class non-POD), but adding access specifiers like private between the two fields may change the layout (in practice, not only in theory).
like image 90
John Zwinck Avatar answered Aug 10 '26 10:08

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!