Re: Size of structs containing unions



"luke" <lroluk1@xxxxxxxxx> writes:
> in Visula C++ 6.0 I have declared a struct like this:
>
> typedef struct _WRITE_INPUT {

Don't use identifiers starting with an underscore; they're reserved to
the implementation. (It's slightly more complex than that, but it's
safest just to avoid them.)

> ULONG DeviceNumber;
> ULONG RegisterNumber;
> union {
> USHORT ShortData;
> UCHAR CharData;
> };
> } WRITE_INPUT;
>
> I can't understand why, sizeof(WRITE_INPUT) returns 12. It should
> return 10, shouldn't it?
>
> sizeof(ULONG) = 4
> sizeof(ULONG) = 4
> sizeof(USHORT) = 2 (longest union field)
>
> 4 + 4 + 2 = 10

The compiler is free to add padding after any member of a structure.
In this case, it's probably adding 2 bytes of padding at the end to
make the size of the structure a multiple of 4, so the ULONG members
will be aligned properly if you have an array of structures.

Incidentally, the names ULONG, USHORT, and UCHAR aren't particularly
helpful. I presume they're typedefs (or macros?) for unsigned long,
unsigned short, and unsigned char, respectively. Why not just use the
names directly?

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Drawstring chars
    ... I see a bunch of glyph handles (since pstro->flAccel has ... typedef struct _FD_GLYPHSET { ... ULONG cGlyphsSupported; ... typedef struct _WCRUN { ...
    (microsoft.public.development.device.drivers)
  • [PATCH 2.6.26 9/25] mdb: Merkeys Kernel Debugger
    ... Netware Style Debugger for Linux written by Jeffrey Vernon Merkey ... +typedef struct _StackFrame { ... ULONG *tCR3; ... +static inline void _cli ...
    (Linux-Kernel)
  • [PATCH 2.6.27-rc1 9/25] mdb: Merkeys Kernel Debugger 2.6.27-rc1
    ... Netware style debugger for Linux written by Jeffrey Vernon Merkey ... +typedef struct _StackFrame { ... ULONG *tCR3; ... +static inline void _cli ...
    (Linux-Kernel)
  • Re: Structure Rupture aka eh?
    ... > typedef struct BLOCK_CHECKSUM_STATE ... > ULONG BlockSize; ... > ULONG Checksum; ...
    (microsoft.public.vc.language)
  • Re: Size of structs containing unions
    ... typedef struct _WRITE_INPUT { ... I think using underscore when declaring objects are fine? ... The compiler is free to add padding after any member of a structure. ... make the size of the structure a multiple of 4, so the ULONG members ...
    (comp.lang.c)