### Thread: Endless loop - why?...

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
7
Rep Power
0

#### Endless loop - why?...

Hi,

Code:
```#include <stdio.h>
#define N 7

int main() {
int i;
int a[N] = {0};
for (i=0; i < 7; i++) {
printf("%d\n", i);
a[N-1-(i+1)] = a[i];
}
return 0;
}```
2. reason behind infinite loop could be:

i and array a is stored in stack.

suppose i is stored in address X
and then array will start from X+sizeof(int)

now in last iteration of loop when i=6

in equestion a[N-1-(i+1)] = a[i];

a[-1]=a[6]

and a[-1] means i because i is stored just before array.

so everytime in last iteration i is restore to 0.
3. a[N-1-(i+1)] = a[i];

When i is zero, N-1-(i+1) is 5.
When i is 6, N-1-(i+1) is -1.

When you try to index a[-1], you are outside the array's bounds. When you write to a[-1], you overwrite a memory location that belongs to something else. That is called clobbering and is the cause of all kinds of weird and unexpected behavior, including the program crashing with a SEGFAULT or the like. In this case, it looks like the local variable i is adjacent to that end of the array and is hence what you're clobbering.

You'd better calculate all the possible values of N-1-(i+1) to ensure that they all are what you expect them to be and that none of them index outside of the array's bounds. It's called testing boundary conditions.