Bug in C compiler(s)

Luke Kendall luke at research.canon.oz.au
Fri Jun 28 06:22:00 AEST 1991


A bug in the Sun and GNU C compilers.  The following tiny program does
not work:

main()
{
    int		i, shift;

    printf("%x\n", 0x10000 >> 1000);

    for (shift = 1, i = 0; i < 5; ++i, shift *= 10)
	printf("%x >> %d = %x\n", 0x10000, shift, 0x10000 >> shift);
}

The output of the program from the Sun C compiler (for a SPARC, SunOS 4.1):

100
10000 >> 1 = 8000
10000 >> 10 = 40
10000 >> 100 = 1000
10000 >> 1000 = 100
10000 >> 10000 = 1

The output of the program from the GNU C compiler (version 1.40):

0
10000 >> 1 = 8000
10000 >> 10 = 40
10000 >> 100 = 1000
10000 >> 1000 = 100
10000 >> 10000 = 1

Looking into the assembly code for the SPARC, it uses an `sra'
instruction (shift-right-arithmetic).  Unfortunately, this instruction
is documented as only working for numbers with the bottom 5 bits set.
In other words, both compilers are failing to mask the right operand
of the shift.
-- 
Luke Kendall, Senior Software Engineer.      | Net:   luke at research.canon.oz.au
Canon Information Systems Research Australia | Phone: +61 2 805 2914
P.O. Box 313 North Ryde, NSW, Australia 2113 | Fax:   +61 2 805 2929




More information about the Comp.sys.sun mailing list