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

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0

    Question Endless loop - why?...


    Hi,
    Could you please help understand why this "for "loop in endless and why "i" is resrt

    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. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    India
    Posts
    95
    Rep Power
    4
    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.
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,171
    Rep Power
    2222
    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.

    Comments on this post

    • eramit2010 agrees : :)
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0
    thanks

IMN logo majestic logo threadwatch logo seochat tools logo