Question

let's say I have:

int test[10];

on a 32bit machine. What if I do:

int b = test[-1];

obviously that's a big no-no when it comes to access an array (out of bound) but what actually happens? Just curious

Am I accessing the 32bit word "before" my array?

int b = *(test - 1);

or just addressing a very far away word (starting at "test" memory location)?

int b = *(test + 0xFFFFFFFF);

0xFFFFFFFF is the two's complement representation of decimal -1

Was it helpful?

Solution

The behaviour of your program is undefined as you are attempting to access an element outside the bounds of the array.

What might be happening is this: Assuming you have a 32 bit int type, you're accessing the 32 bits of memory on the stack (if any) before test[0] and are casting this to an int. Your process may not even own this memory. Not good.

OTHER TIPS

Whatever happens, you get undefined behaviour since pointer arithmetic is only defined within an array (including the one-past-the-end position).

A better question might be:

int test[10];
int * t1 = test+1;
int b = t1[-1];      // Is this defined behaviour?

The answer to this is yes. The definition of subscripting (C++11 5.2.1) is:

The expression E1[E2] is identical (by definition) to *((E1)+(E2))

so this is equivalent to *((t1)+(-1)). The definition of pointer addition (C++11 5.7/5) is for all integer types, signed or unsigned, so nothing will cause -1 to be converted into an unsigned type; so the expression is equivalent to *(t1-1), which is well-defined since t1-1 is within the array bounds.

The C++ standard says that it's undefined behavior and illegal. What this means in practice is that anything could happen, and the anything can vary by hardware, compiler, options, and anything else you can think of. Since anything could happen there isn't a lot of point in speculating about what might happen with a particular hardware/compiler combination.

The official answer is that the behavior is undefined. Unofficially, you are trying to access the integer before the start of the array. This means that you instruct the computer to calculate the address that precedes the start of the array by 4 bytes (in your case). Whether this operation will success or not depends on multiple factors. Some of them are whether the array is going to be allocated on the stack segment or static data segment, where specifically the location of that address is going to be. On a general purpose machine (windows/linux) you are likely to get a garbage value as a result but it may also result in a memory violation error if the address happens to be somewhere where the process is not authorized to access. What may happen on a specialized hardware is anybody's guess.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top