Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Layout for struct prefix

The C/C++ languages don't reorder struct members in memory and never insert padding before the first member. But if I have 2 structures that start with the same members, can I cast between them if I only access the common members? In other words, is struct layout greedy? My concrete case is casting between VIDEOINFOHEADER and VIDEOINFOHEADER2

like image 801
Bruno Martinez Avatar asked Dec 26 '13 17:12

Bruno Martinez


2 Answers

The C++ standard contains the following statement which, however, only applies to unions (9.2 [class.member] paragraph 19):

If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

I didn't see any other guarantee with respect to partially defined structures in either the C or the C++ standard. That doesn't mean it isn't there, though, just that I haven't found it with a quick scan of a couple of relevant sections.

like image 181
Dietmar Kühl Avatar answered Oct 17 '22 15:10

Dietmar Kühl


Short answer: yes. Mostly.

Compilers cannot re-order struct members: true. I'm not so sure about the padding, IFAIR structure member alignment is implementation defined.

But, a compiler is consistent when laying out structures. It has to be, or you'd never be able to write and then read back structures to files. And most compilers use 'sane' rules for structure layout, so you can write from one program and read in with another, even if they are different compilers on different systems.

Most of the time. There are no exactly defined rules for structure layout. So occasionally you get bitten by relying on the "natural" layout to match, when it doesn't. But in this case, you should be safe.

like image 1
Chris J. Kiick Avatar answered Oct 17 '22 17:10

Chris J. Kiick