Unions | Microsoft Docs
https://docs.microsoft.com/en-us/cpp/cp ... ew=vs-2017
- So a union is a bit like a drop-down list, you choose one of the possible items.A union is a user-defined type in which all members share the same memory location. This means that at any given time a union can contain no more than one object from its list of members. It also means that no matter how many members a union has, it always uses only enough memory to store the largest member.
- One query is, sometimes the possible items are of different sizes, in such cases, should it be assumed that the size of the union is always the size of the largest member? (Whether the largest member is used or not.)
Code: Select all
;==================================================
typedef struct _OVERLAPPED {
ULONG_PTR Internal;
ULONG_PTR InternalHigh;
union {
struct {
DWORD Offset;
DWORD OffsetHigh;
} DUMMYSTRUCTNAME;
PVOID Pointer;
} DUMMYUNIONNAME;
HANDLE hEvent;
} OVERLAPPED, *LPOVERLAPPED;
;size (x64): 8 + 8 + Max(4+4,8) + 8 = 32
;size (x32): 4 + 4 + Max(4+4,4) + 4 = 20
;==================================================
typedef struct _STRRET {
UINT uType;
union {
LPWSTR pOleStr;
UINT uOffset;
CHAR cStr[MAX_PATH];
};
} STRRET, *LPSTRRET;
;size (x64): 4+(4) + Max(8,4+(4),260+(4)) = 272
;size (x32): 4 + Max(4,4,260) = 264
;==================================================
- And, if an LPWSTR is present (8 bytes), the struct size must be a multiple of 8, whereas for the other 2 members, the struct size must be a multiple of 4 since the biggest member is a UINT (4 bytes).
- So in x64:
UINT uType; LPWSTR pOleStr; [size: 4(4)+8 = 16]
UINT uType; UINT uOffset; [size: 4+4 = 8]
UINT uType; CHAR cStr[MAX_PATH]; [size: 4+260 = 264]
UINT uType; CHAR cStr[MAX_PATH]; [size: 4+(4)+260+(4) = 272] [taking into account LPWSTR pOleStr]
Where 272 is the value returned by sizeof().
- So, in x64, we consider 'CHAR cStr[MAX_PATH]', 260 bytes which could start at offset 4, but also consider 'LPWSTR pOleStr', which must start at offset 8, and demands an overall struct size that is a multiple of 8. So, should we combine all of the criteria when considering the union? E.g. the size of union option 3 with the padding requirements of union option 1.
- I also started this thread in case anyone has anything else interesting to say about unions. Thanks.