local variable gets modified suddenly

Hello everyone
A student of mine wrote the following code and compiled it on Ubuntu Server OS 11.4, using g++ v 4.5.2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
        int  n = 5;

        float matrix[25]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
        float new_mat[16];
        int k=0;
        int iter=0;

        for (iter=0; iter < 5 ; iter++)
        {
                for (int j=n;j<n*n;j=j+1)
                {
                        if ((j-iter)%n == 0)
                                j++;

                        new_mat[k]=matrix[j];
                        k++;
                }
                cout<<"n= "<<n<<endl;
        }
        return 0;
}


The output appears as follows:


n= 5
n= 1086324736
n= 1086324736
n= 1086324736
n= 1086324736


Apparently, something somewhere is overwriting n. I used -Wall and -Wextra switches with the build as well, but didn't get any warnings or errors on compile. I then used the -ggdb switch to compile it with debugging symbols and opened the executable in gdb. I checked the addresses for the variables, and here are the results:


(gdb) print &n
$1 = (int *) 0x7fffffffe620
(gdb) print &matrix[0]
$2 = (float *) 0x7fffffffe570
(gdb) print &matrix[24]
$3 = (float *) 0x7fffffffe5d0
(gdb) print &new_mat[14]
$5 = (float *) 0x7fffffffe618
(gdb) print &new_mat[0]
$6 = (float *) 0x7fffffffe5e0


Do you see anything suspicious that I don't? Could it simply be a bug in the compiler or the run time? Shall I maybe file a bug report with GNU?
Thanks and best regards
I forgot to mention that if I declared another variable:

 
int m = n;


and then use it in the inner for loop:

 
for (int j=n;j<m*m;j=j+1)


the problem goes away. This is strange. The student spent a long time trying to find the problem and, needless to say, is blaming it on the Linux OS. :-)
Whoops! My bad. I should've debugged it more thoroughly. Now, I see that the variable k goes beyond the new_mat array's bounds to 16. Which, obviously overwrites the variable n. When I declare m, n probbaly moves further in the stack and, therefore, the overwrite affects m and not n, so the output seems decievingly correct.
Topic archived. No new replies allowed.