Weird warning message, it makes no sense
-
I get a weird warning message in Qt creator:
/home/daniel/Documents/Qt/MMKPHV/mmkphv.cpp:730: warning: 'tr[9]' may be used uninitialized in this function [-Wmaybe-uninitialized]
tr[k] += res[i][j][k] - res[i][sj][k];
^void MMKPH::rndLcl(int seed, int its, int lcl) { int i, j, k, l, v, q, sj, r[MAX_DIMS], tr[MAX_DIMS], ti[MAX_LCLS], tj[MAX_LCLS]; bool flg; srand(seed); for (k = 0; k < dims; k++) { r[k] = 0; for (i = 0; i < cla; i++) r[k] += res[i][sol[i]][k]; } for (l = 0; l < its; l++) { v = 0; for (k = 0; k < dims; k++) tr[k] = 0; // <- it's initialised here! for (q = 0; q < lcl; q++) { i = rndU(0, cla - 1); j = rndU(0, items[i] - 1); ti[q] = i; tj[q] = j; sj = sol[i]; v += val[i][j] - val[i][sj]; for (k = 0; k < dims; k++) tr[k] += res[i][j][k] - res[i][sj][k]; // <- this is the line of the warning } if (v > 0) { ... } } }
-
Hi,
What is dims ?
What is its value ?
Where does it come from ? -
In addition to what @SGaist said, if
- dims is a global variable and
- dims is not const
then it might be possible that dims is changed (e.g. by another thread) while your function is running.
To be save, I'd init tr completely to zero (e.g. with memset, or by looping up to MAX_DIMS).
And to go a step further, it would not hurt to init all other variables too.
Regards
-
@Guerrian said in Weird warning message, it makes no sense:
r[MAX_DIMS], tr[MAX_DIMS], ti[MAX_LCLS], tj[MAX_LCLS];
You might consider using vectors. They can make your life easier:
std::vector<int> vect1(10); // 10 elements with default initializer std::vector<int> vect2(10,1); // 10 elements inited to 1 // easy looping for(auto& v: vect1){ qInfo() << v; } for(auto& v: vect2){ qInfo() << v; }
I don't know your requirements though. So YMMV.
-
@Guerrian said in Weird warning message, it makes no sense:
Why wouldn't all elements be initialised, the init loop will always execute?
Did you debug your code to see what happens? This is fastest way to find out what is happening.
-
@Guerrian
I don't quite get your problem, dims is a non constant member variable, that may or may not be changed between the 2 for loops.the code model can't tell and is therefore warning you. If you're sure that everything will always be fine, ignore it.
if you want to get rid of the warning. shadow it locally.
void MMKPH::rndLcl(int seed, int its, int lcl) { const int dims = this->dims; .....