eeegnu
eeegnu

Reputation: 446

Locally compiled c++ code is improperly looping

The following never terminates on my system.

#include <iostream>

using namespace std;

int main(){
    int solutions[1000][4] = {};
    

    for(int a=0; 3*a<=1000; a++){
        for(int b=0; 5*b<=1000; b++){
            for(int c=0; 7*c<=1000; c++){
                cout << "enter" << "\t" << a << "\t" << b << "\t" << c << endl;
                if (3*a+5*b+7*c > 1000) {break;}
                solutions[3*a+5*b+7*c][0] = a;
                solutions[3*a+5*b+7*c][1] = b;
                solutions[3*a+5*b+7*c][2] = c;
                solutions[3*a+5*b+7*c][3] = 1;
                cout << "exit" << "\t" << a << "\t" << b << "\t" << c << endl << endl;
            }
        }
    }
}

I'm completely stumped, so I decided to print a log of variable changes. It makes it to 4 iterations of b, and then when c hits 140, it loops back to 0. Log looks like this

...
enter   0       4       137
exit    0       4       137

enter   0       4       138
exit    0       4       138

enter   0       4       139
exit    0       4       139

enter   0       4       140
exit    0       4       0

enter   0       4       1
exit    0       4       1

enter   0       4       2
exit    0       4       2

enter   0       4       3
exit    0       4       3
...

I compiled this using g++ B.cpp -o B.exe, and then just ran the executable. The exact code (with logging commented out) terminates properly online at http://cpp.sh/. My compiler version is g++ (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 5.3.0. What could be going wrong here?

Upvotes: 0

Views: 22

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

When a = 0, b = 4, c = 140, 3*a+5*b+7*c becomes 1000 and write to out-of-bounds solution[1000] happens. It seems this out-of-bound write happened to break the loop counter.

Allocate one more element to avoid this out-of-bounds write.

    int solutions[1001][4] = {};

Upvotes: 1

Related Questions