[comp.sys.atari.st] Turbo C v1.0 bug?

joep@tnosoes.UUCP (Joep Mathijssen) (02/28/90)

||   #include <stdio.h>
||   
||   long tab[9000];
||   
||   main()
||   {
||       int i;
||       long j;
||   
||       i = 0x2000;      /* 0x2000 = 8192 */
||       j = 0x2000L;
||       fprintf(stderr, "%lx, %lx\n", &(tab[i]), &(tab[j]));
||   }
||   
||   

RESULT:

||   561b2, 661b2

Can anybody explain the difference in the result when using an 'int' or
'long int' as array-index?

Joep,


PS: don't tell me this is a feature!
===============================================================================
Joep Mathijssen
TNO Institute for Perception
P.O. Box 23          		Phone : +31 34 63 562 11
3769 ZG  Soesterberg    	E-mail: tnosoes!joep@mcvax.cwi.nl
The Netherlands         	    or: uunet!mcvax!tnosoes!joep
===============================================================================

jfbruno@rodan.acs.syr.edu (John F. Bruno) (03/02/90)

In article <870@tnosoes.UUCP> joep@tnosoes.UUCP (Joep Mathijssen) writes:
>||   #include <stdio.h>
>||   long tab[9000];
>||   main()
>||   {
>||       int i;
>||       long j;
>||       i = 0x2000;      /* 0x2000 = 8192 */
>||       j = 0x2000L;
>||       fprintf(stderr, "%lx, %lx\n", &(tab[i]), &(tab[j]));
>||   }
>RESULT:
>||   561b2, 661b2
>Can anybody explain the difference in the result when using an 'int' or
>'long int' as array-index?
>Joep,
>PS: don't tell me this is a feature!

The first thing that comes to mind here is that the compiler is not
converting j to an int before placing i and j on the stack.  If this is
the case, and assuming i and j get put on the stack first, the stack would
look like this:

           0x2000 (lsw of j)
           0x0000 (msw of j)
           0x2000 (i)

Then, when it goes to pull two ints off the stack, it gets 0x2000 (which
gets substituted for j) and 0x0000 (which gets substituted for i. Now, we have:

    fprintf(stderr,"%lx, %lx\n", &(tab[0x0000]), &(tab[0x2000]) );

Now we have two different addresses that are offset by 0x2000 x sizeof(long)
if sizeof(long) == 8, that would explain the difference you got, but I thought
a long was 4 bytes... But this is how you could get different results by
passing the wrong size object, anyway.  If you want to use a long as an
array index, try this:

#define tab(X) (*(tab + sizeof(long)*X))

Then you can do things like:

tab(100000L)=4567L;
printf("ADDR=%lx, VALUE=%ld\n",&tab(10000L),tab(10000L));

---jb

P.S. - I highly recommend turning on every warning that the compiler
supports, this will usually catch things like using longs as array
indeces, and other nasty litte oversights.