2

Here a portion of the loop I used to implement insertion sort algorithm:

while (j > 0 && values[j - 1] > actualElement) 
{
     // place the unsorted element inside the correct position in the sorted side 
     int sorted = values[j - 1];
     values[j - 1] = actualElement;
     values[j] = sorted;
     j--;
}
values[j] = actualElement;

if the condition is j >= 0 obviously I can enter in values[-1](I thought it was inacessible or did not exist), when this happen I get in position [0] a big number that is the number in values[-1](I reckon).

On the contray if I enter in position n, I obtain 0 (is this the termiantor of the array?).

1

In C, there's nothing prevents you from doing such thing as trying to access illegal array indices. Some other languages (e.g., Java) throws an exception at run time if you tried to perform such operation.

In C, however, if values is an n-element array, then values[-1] starts at sizeof (values[0]) bytes right before the start of values[0]. For example, if values was an array of 32-bit ints and values[0] starts at location 100, then values[-1] starts at location 96 (byte 100 - 4 bytes).

Similarly, if n was 10 and values[9] starts at location 140 then values[10] starts at location 144 (byte 140 + 4 bytes).

Tools like valgrind may help you figure that out in order to fix it. valgrind's invalid read/write messages include that sort of bugs.

As the other answers has pointed out, trying to access locations that do not belong to you may result in what's known as an undefined behavior and you may get back garbage values or your program may crash.

0

If you access memory that hasn't been allocated to you, then what you get is whatever happens to be in there. It could be other variables that you've created, it could be the code itself.

You should not rely on it.

0

Starting with your last question, is zero a terminator of array? Actually you could use it that way, but I would strictly recommend to avoid any such practice. This is because the value 0 is initialized to a variable by the compiler by default(if explicitly programmer does not initialize the variable). So all the array index that you haven't touched yet, are set to zero. Then what is that big number assigned to values[-1]?

That's the garbage value. It is simply a value that is stored on that memory location previously or may be depending on your system's architecture, it is assigned. But a better understanding to them should be in considering them as in-determinant values, and working with them shall lead to unexpected results, just like the case you tried to access values[-1]

Now another question arises that when are garbage values assigned and when are 0s. Explicitly uninitialized variables are assigned the value 0 if the variable is static or has a global scope, else, garbage values are assigned.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .