Though it may sound a bit different from my regular posts, I just want to post it. It is pure technical and those who don't want to give their brain muscles a workout may skip this. It was related to 64 bit porting and negative array indices.

I was porting an application from 32-bit windows to 64-bit windows and found an interesting result. Actually in our code we use negative array indexes very frequently, these things work fine on a 32 bit M/C but meet some horrible results on 64 bit machine. I am explaining here what the problem was:

Many books define that negative array indices show indefinite behavior but what I investigated is as follows. Actually on any system (32 bit or 64 bit) array indices are taken as integer (4 bytes). When we give any negative indices to the array, 2's complement of the index is added to base address of the array. It generally overflows the 32 bit limits and since in 32 bit systems address space is limited to 32 bit we ignore all the bits more than 31st bit and basically got a value "Base - index". But in 64 bits we can't ignore that overflowed value as that makes a validbut junk location and in turn refer to a junk location.

Example:

For example I take an array "akash" and found it's base address as 0x4162b654 while debugging.

&akash[0] = 0x4162b654

On 32 bit machine, while performing following operation it was giving me following result:

&akash[ 0 - 3 - 1 ] = 0x4162b650

Explanation:

&akash[0] = 0x4162b654

&akash[ 0 - 3 - 1 ] = 0x4162b654 - 3 - 1 = 0x4162b654 - 0x00000003 - 0x00000001

= 0x4162b654 + 0xfffffffd + 0xffffffff (converted in 2's complements)

= 0x24162b650

= 0x4162b650 (After ignoring bits more than 31st)

But in 64 bit system, if we take the same address for array 'akash', we can't ignore '2' and got to the address 0x24162b650., which is the reason for all the problems.

So this was the reason that for 64 bit system why I got unexpected crashes in the same code. The solution to avoid these situation is to type cast array indexes as ptrdiff_t like akash[ptrdiff_t(0-3-1)].

Also I want to give some more observations and information to the readers. I was using visualstudio8 on both 32 and 64 bit machines. OSes installed were 'win-xp professional' and 'win-xp professional 64-bit' respectively. I have also caught one bug for visual studio. When watch the address of akash[0-3-1] on 64 bit machines then it shows 0x000000004162b650 but program crashes as it can not access memory location 0x000000024162b650. This is actually a bug and need to be resolved by Microsoft coz what you are seeing while debugging, your EXE should follow the same. I am going to log a bug against visual studio in this regard.