[dmd-internals] Struct equality

Iain Buclaw ibuclaw at ubuntu.com
Tue Nov 13 08:27:52 PST 2012


On 6 November 2012 16:42, Shahid <govellius at gmail.com> wrote:
> I've been poking around in the backend when I noticed that structs are
> being compared with cod2's cdmemcmp(), dmd makes sure that struct
> padding is always initialised to 0 ( TDPL page268 7.1.11 )
> so it is not a problem...
>
> However Given:
> -----
> struct S
> {
>     byte a;
>     int  b;
> }
> static assert( S.sizeof == 8 );
> static assert( S.a.offsetof == 0 );
> static assert( S.b.offsetof == 4 );
> -----
>
>
> Question 1. What if the struct comes from C?
> ============================================
> In C struct padding values are "unspecified"
>
> To Quote from C99 (6.2.6.1)
>> When a value is stored in an object of structure or union type,
>> including in a member object, the bytes of the object representation
>> that correspond to any padding bytes take unspecified values.
>
> -----

As structural equality in D is done with memcmp, you should ensure
that the C function initialises the struct/union var with memset
before assigning values.


>
> Question 2. What about Void Initializations?
> ============================================
> In func2() all fields are eventually initialised,
> but the padding is undefined.
>
> -----

This is a potential problem.


Regards,
-- 
Iain Buclaw

*(p < e ? p++ : p) = (c & 0x0f) + '0';


More information about the dmd-internals mailing list