0

I have one doubt in the following snippet. Actually I am initializing all the array index to zero in following code, but this for loop is going infinitely. I found reason that we are trying to access the 26th index of array, so that value gets initialized to zero again since there is 0 to 25 index. So the for loop is going infinitely. Explain if any one the actual reason behind this stuff.

int array[26];
int i; 
for (i = 0; i <= 26; i++) 
    array[i]= 0;

3 Answers 3

10

You have to use i < 26; otherwise you exceed the array bounds.

Due to the layout of the stack on most systems array[26] will point to the memory used for i which results in the loop starting again since you loop body is setting i to 0 instead of an appropriate array element.

Note that you can simply use int array[36] = { 0 }; to create the array with all elements being set to 0.

Sign up to request clarification or add additional context in comments.

4 Comments

when we are exceeding index , it suppose to change index values not the i value. it seems to be very weired thing. if some body use unknowingly for some other purpose not to initialize . it can big make damage.
Well you write to a memory location outside of the array. Obviously there is something at this location - and as I said, usually it's the var defined after the array.
@pavun_cool: Yes, it can "make big damage". You must be careful not to write past the end of a buffer. This is the cause of a tremendous number of bugs in the software world, some of which have caused space rockets to explode. Welcome to low-level programming.
You could run your program through valgrind - it usually detects problems like off-by-ones or plain invalid memory accesses and shows you a warning.
1

Maybe i is located after array in the memory and it become 0 when i=26 in the loop. I.e. &array[26] == &i.

Comments

0

I found reason that we are trying to access the 26th index of array, so that value gets initialized to zero again since there is 0 to 25 index. So the for loop is going infinitely.

The reason is that your loop variable i goes from 0 to 26 inclusive. But there is no array[26].. only array[0] to array[25] (which is a total of 26 elements).

You are invoking undefined behaviour by writing to array[26]; it just so happens in your execution run that i was laid out just after array in memory, and you were accidentally writing 0 to i due to the erroneous write. This may have caused an infinite loop.

Instead write:

int array[26];
int i;
for (i = 0; i < 26; i++) {
   array[i] = 0; 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.