Search code examples
c++loopsfor-loopcorruption

For loop variable going to hell for seemingly no reason?


I have run into what seems to be a very obscure bug. My program involves looping some code for a long time, and eventually running some functions in the loop. Weirdly, after I run a specific function, my for loop variable, 'z', jumps from 3200 to somewhere around 1059760811 (it changes every time). The function does not naturally use the loop variable, so I honestly have no idea what is happening here.

The entire code is too long to paste here, so I will try to paste only the important parts, with the relevant functions first and the for loop after:

void enterdata(float dpoint,int num){
        autodata[num] += dpoint;
    }
float autocorr(){
        float autocorrelation = 0;
        for(int a = 0; a<SIZEX; a++)
        {
            for(int b = 0; b<SIZEY; b++)
            {
                if(grid[a][b] == reference[a][b]){autocorrelation++;}
            }
        }
        autocorrelation /= SIZEX*SIZEY;
        autocorrelation -= 0.333333333333;
        return autocorrelation;
    }

for (long z = 0.0; z<MAXTIME; z++)
    {
        for (long k=0; k<TIMESTEP; k++)
        {
            grid.pairswap();
        }
        if (z == autostart_time)
        {
            grid.getreference();
            signal = 1; // signal is used in the next if statement to verify that the autocorrelation has a reference.
        }
        if ((z*10)%dataint == 0)
        {
            if (signal == 1) {
            //!!! this is the important segment!!!
            cout << z << " before\n";
            grid.enterdata(grid.autocorr(),count);
            cout << z << " after\n";
            cout << grid.autocorr() << " (number returned by function)\n";
            count++;
            }
        }
        if (z%(dataint*10) == 0) { dataint *= 10; }
    }

From the "important segment" marked in the code, this is my output:

3200 before, 1059760811 after, 0.666667 (number returned by function)

Clearly, something weird is happening to the 'z' variable during the function. I have also become convinced that it is the enterdata function and not the autocorrelation function from tests running each separately.

I have no idea how to fix this, or what is going on. Help?!?!?

Thanks!


Solution

  • Looks like you may have a Stack Overflow issue in your enterdata function.

    Writing to before the array starts or past the end of the array result in undefined behavior, including writing over variables already on the stack.