Reputation: 259
I have declared an array of length N (suppose). Now, I assign some values to the elements of this array using a loop (the loop variable is used as the array's index). The code's as follows:
int main()
{
int arr[4], j;
for(j=0; j<10; j++)
{
printf("%d\n", j);
arr[j] = 0;
sleep(1);
printf("%d\n\n", j);
}
return 0;
}
I expected the output to be 0 1 2 .. 9. But what actually happened was that j got reset to 0 when the assignment arr[N+2]=0 (arr[6]=0, in this case) was executed in the loop. What's actually happening here? Am I missing something?
Upvotes: 3
Views: 2901
Reputation: 89202
Your array has 4 elements and your index is out of range so you are just stomping on memory.
Given the code here, I'd expect arr[4]
to reset the array, but since you mentioned that it's of length N
and N+2
is what causes it, there might be some padding in your stack. In any case, when you declare the array and j
, they are put on the stack. In your case, j
is in a position such that when your index is out of bounds you are accessing the memory where j
is.
Upvotes: 8
Reputation: 127508
Your array is overflowing. You defined it like this with 4 elements:
int arr[4]
But you're trying to assign 10 elements.
j
is apparently located immediately after the array, so when you assign arr[6] = 0
, you're clearing j
.
Upvotes: 2
Reputation: 4441
the behaviour of the code is undefined as it has a bug. arr has a size of 4 but you are indexing past this size with j
Upvotes: 3