[comp.os.minix] Bug in PC C compiler

csc239@central1.lancaster.ac.uk (A. S. Lunn) (08/21/90)

I've found a bug in the minix C compiler. Try the following program..

main()
{
	char Buffer[256];
	int  BufferPtr = 0;

	Buffer[BufferPtr++] = 1;
/* printf ("%d\n",BufferPtr); */
	Buffer[BufferPtr++] = 2;
/* printf ("%d\n",BufferPtr); */
	Buffer[BufferPtr++] = 3;

	printf ("%d %d %d %d\n",Buffer[0],Buffer[1],Buffer[2],BufferPtr);
}

Ignore the commented out printf's for the moment. You would expect this program
to print out 

1 2 3 3

What does it do?

3 0 0 3.

Now uncomment the first printf, and you get
1
1 2 3 3

Recomment the first printf and uncomment the second and now you get
2
2 0 3 3

Lastly uncomment both printf's
1
2
1 2 3 3.

Looking at the assembly language produced by asld explains whats going on. 
I've chopped off the code for crtso and fprintf and the last printf of main. 
The second printf in uncommented here. 


			.globl _main
			.text
			_main:
001E 55			push bp		
001F 89E5		mov bp,sp	| setup access to parameters
0021 81EC0201		sub sp,#258	| make space for array and BufferPtr
0025 56			push si		| save si on stack
0026 31F6		xor si,si	| zero si.si used as BufferPtr
0028 89F0		mov ax,si	| Zero ax
002A 46			inc si		| BufferPtr++, but ax original value
002B 8D9E00FF		lea bx,-256(bp)	| work out start address of array
002F 01C3		add bx,ax	| add on offset to element required
0031 C60701		movb (bx),#1	| put the one in the element
| Bug here.
0034 46			inc si		| BufferPtr++
0035 8D9E00FF		lea bx,-256(bp) | address of array
0039 01C3		add bx,ax	| Add on offset
003B C60702		movb (bx),#2	| store value in array
003E 56			push si		| get ready for printf call
003F B8E208		mov ax,#_1
0042 50			push ax
0043 E85300		call _printf	| call printf
0046 5B			pop bx
0047 5B			pop bx
0048 89F0		mov ax,si	| load ax with BufferPtr
004A 46			inc si		| BufferPtr++
004B 8D9E00FF		lea bx,-256(bp)	| address of array
004F 01C3		add bx,ax	| add on offset 
0051 C60703		movb (bx),#3	| store in array

The bug is where I've put the comment 'Bug here'. The instruction mov ax,si
needs inserting here to load ax with the offset into the array. The printf 
statement uses ax in setting up for the call and so is correctly used with 
the next store into the array. This makes me think its the optimiser that 
introducing the bug. 

Is this a known bug and is there a fix for it?

	Andrew Lunn

	csc239@uk.ac.lancaster.central1      on JANET
						Computing Department
						University Of Lancaster
						England.