C++ memory: deleting an unused array of bool can change the result from right to wrong -
C++ memory: deleting an unused array of bool can change the result from right to wrong -
i trying solve project euler problem 88, , did without much effort; however, find seemingly irrelevant code in programme affecting result. here's finish code (it's not short, cannot locate error. believe obvious more experienced eyes, please read description first):
#include <iostream> #include <set> using namespace std; bool m[24001][12001]; bool p[24001]; // <------------ deleting line cause error in result! long long answer[12001]; int main() { long long i; long long j; long long l; set<long long> all; long long s = 0; (i = 0; <= 24000; i++) { (j = 0; j <= 12000; j++) { m[i][j] = false; } } m[1][1] = true; (i = 2; <= 24000; i++) { m[i][1] = true; (j = 2; (j <= i) && (i * j <=24000); j++) { (l = 1; l <= i; l++) { if (m[i][l]) { m[i * j][l + 1 + (i * j) - - j] = true; } } } } (i = 0; <= 24000; i++) { (j = 0; j <= 12000; j++) { if (m[i][j] && (answer[j] == 0)) { answer[j] = i; } } } (i = 2; <= 12000; i++) { cout << answer[i] << endl; all.insert(answer[i]); } cout << all.size() << endl; (set<long long>::iterator = all.begin(); != all.end(); it++) { //cout << *it << endl; s += *it; } cout << s << endl; }
with "useless" bool array, answers right, between 0 , 24000; without it, answers in middle got corrupted , become big numbers.
i confused now; why unused array impact middle of reply array?
thanks , sorry long code! grateful if edit code improve example, son't know code.
as requested, adding answer.
you writing beyond bounds of array m
somewhere, when unused array p
exists, m
overwrites in contents doesn't impact reply array 1 time p
removed overwriting happens in reply array showing problems.
overwriting beyond bounds of array undefined behavior , causes programme ill-formed. undefined behavior safe bets off , behavior possible. while programme may work or crash or give wrong results.practically, possible , behavior may or may not explainable.
c++ arrays debugging memory
Comments
Post a Comment