tinycc-devel
[Top][All Lists]
Advanced

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

Re: [Tinycc-devel] Bug Report (offset+cast)


From: kf
Subject: Re: [Tinycc-devel] Bug Report (offset+cast)
Date: Fri, 11 May 2007 21:13:43 +0300

On 5/11/07, Dave Dodge <address@hidden> wrote:
On Fri, May 11, 2007 at 11:31:28AM -0400, David A. Wheeler wrote:
> Gil Dabah:
> > > It seems you can't cast a pointer from a specified offset:
> > >
> > > char* s = "\x34\x34\x12";
> > > short word = *(short*)&s[1]; // <--buggy
> > > printf("%x", word);
> > >
> > > will print 34 instead of 1234 (on LE machine, of course).
>
> Confirmed, it's a bug in tcc.
>
> kf:
> > Happens here too. However,
> >
> > short word = *(short*)(s+1);
> > works as expected.
>
> Confirmed, that one works correctly.

Well, the term "correctly" is a bit suspect.  You can't convert an
arbitrary char* to a short* and dereference it without risking
undefined behavior, because among other things there's no guarantee
that the pointed-to location will be aligned properly as a short.

That code on a Sparc (with any compiler) will almost certainly core
dump with a bus error.  On IA64 (with gcc) it traps and emits an
"unaligned access..." message before continuing.  x86 only lets you
get away with this sort of thing because of its loose alignment
behavior; other real-world systems are much less forgiving.

This is true, of course. I sometimes use something like:

#define CAST(x) ({short __foo; memcpy(&__foo, &x, sizeof (short)); __foo; })

and then:

short word = CAST(s+1);

to be portable (no bus errors on Sparc), and efficient, as this
translates to a single mov instruction on x86, i.e. something like
movw 0x1234,(word) with gcc -O3. But tcc probably produces bad code
for this, emitting a call to memcpy...

kf


                                                  -Dave Dodge


_______________________________________________
Tinycc-devel mailing list
address@hidden
http://lists.nongnu.org/mailman/listinfo/tinycc-devel






reply via email to

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