RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Mar 31, 2009

Be Careful of Negative Array Indices

While porting a 32-bit application to a 64-bit version, I discovered an interesting effect. The original code used negative array indexes frequently, which worked fine on a 32-bit machine, but caused some horrible results on a 64-bit machine. This tip explains the problem:

Many books that discuss negative array indices show indefinite behavior. Actually, on any systems (both 32- and 64-bit), C++ uses integer (four byte) array indices. When you assign any negative index to the array, the two's complement of the index gets added to the array base address. That generally overflows the 32-bit limits. In 32-bit systems the address space is limited to 32 bits, so the system ignores all bits beyond the 31st bit. That means you get an address value of Base - index. But in the 64-bit world, you can't ignore the overflow value, because it's a valid location, so for negative array indices, the address can point to a "junk" location.

For example, suppose you have an array akash, which the debugger reveals has a base address of 0x4162b654:

&akash[0] = 0x4162b654

On a 32-bit machine, performing the following operation gave this result:

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

Here's my 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 a 64-bit system, if you begin with the same address for array akash, you can't ignore the leftmost 2 in the preceding result, so you get the address 0x24162b650, which is the reason for all the problems.

The workaround for avoiding such situations is to typecast array indexes as ptrdiff_t, for example: akash[ptrdiff_t(0-3-1)].

For completeness, I was using Visual Studio 8 on both the 32 and 64-bit machines, running under Windows XP Professional, and Windows XP Professional 64-bit, respectively. I also noticed a possible bug in Visual Studio. When watching the address of akash[0-3-1] on 64-bit machines, the debugger shows 0x000000004162b650—but the program crashes, because it can't access that memory location.

Akash Aggarwal
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date