tinycc-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Tinycc-devel] Patch: Permit certain pointer assignments (grischka-2


From: Dave Dodge
Subject: Re: [Tinycc-devel] Patch: Permit certain pointer assignments (grischka-2005-09-25 case_7)
Date: Fri, 4 May 2007 03:53:35 -0400
User-agent: Mutt/1.5.12-2006-07-14

On Thu, May 03, 2007 at 09:56:23AM -0400, David A. Wheeler wrote:
> In practice, given:
>     struct _s1 { int a, b, c; } *p1 = NULL;
> gcc will accept the following assignment without even a warning:
>     struct _s2 { int a, b, c; } *p2 = p1;
> (Notice that the struct tags are different, but no warning is given.)

In the same translation unit?  Even old gcc 3.3.3 with no options complains:

  warning: initialization from incompatible pointer type

It's a constraint violation, so the Standard requires a diagnostic for
it if it's visible to the compiler.

Aside: it's actually pretty important that the compiler complain about
this sort of thing.  Some applications use struct encapsulation
entirely to get extra type-checking for basic types.  For example say
you've got some code that's dealing with both byte offsets and block
offsets in a region of memory; both offsets are simple integers, but
if someone uses a byte offset where a block offset is expected (or
vice versa) it could lead to subtle and hard-to-debug failures.  So
you can do something like this:

  typedef struct _byteoffset { unsigned int x; } byteoffset_T;
  typedef struct _blockoffset { unsigned int x; } blockoffset_T;

to effectively make two incompatible "unsigned int" types.  Then a
function can explicitly request a byte offset:

  void foo(byteoffset_T);

and the compiler will complain if someone screws up and passes a block
offset.  Of course the hope is that the compiler will optimize away
the struct wrapper, so it ends up being just a compile-time check with
no impact on execution speed.  As a real-world example, you can see
the Linux kernel using this technique in page.h for types such as
pgd_t and pmd_t.

                                                  -Dave Dodge




reply via email to

[Prev in Thread] Current Thread [Next in Thread]