I don't understand why there is a problem with my code. I've made sure to initialize every value in my 2D array, so there shouldn't be an uninitialized value error anywhere!
Note: I cannot use std::vector
for this project. I'm also using different functions instead of std::min
because I'm not allowed to import algorithm
for this project.
This is the error reported by clang-tidy:
2nd function call argument is an uninitialized value
Here is my code (error only occurs on line 17):
int** SeamCarver::CarvingSeamVertical() const {
int** energies = new int*[height_];
for (unsigned int row = 0; row < height_; row++) {
energies[row] = new int[width_];
for (unsigned int col = 0; col < width_; col++) {
energies[row][col] = 0; // initializes every value in the 2D array to zero
}
}
for (unsigned int col = 0; col < width_; col++) {
energies[height_ - 1][col] = this->GetEnergy(height_ - 1, (int)col);
}
for (int row = height_ - 2; row >= 0; row--) {
for (int col = 0; col < width_; col++) {
int best = 0;
if (col == 0) { //error occurs here v
best = FindMinTwo(energies[row + 1][col], energies[row + 1][col + 1]);
} else if (col == width_ - 1) {
best = FindMinTwo(energies[row + 1][col - 1], energies[row + 1][col]);
} else {
best = FindMinThree(energies[row + 1][col - 1],
energies[row + 1][col],
energies[row + 1][col + 1]);
}
energies[row][col] = this->GetEnergy(row, col) + best;
}
}
return energies;
} // energies is properly deallocated by the function that uses it
I've tried changing the ints to unsigned ints, but the error didn't go away. I also should not encounter out-of-bounds access errors, since row starts at height - 2
and the highest value of row accessed within the loop is height - 1
.
For some reason, adding a statement which prints every value in the array makes the error go away.
clang-tidy doesn't make assumptions for you. For example, it doesn't assume that width_
is greater than 1. And indeed, if width_ == 1
, you get a bunch of problems and clang-tidy warns about some of them.
Add assert(width_ > 1)
at the beginning, and the error will go away. Or, if you are not willing to assert that, revise your algorithm to correctly handle the case of width_ <= 1
.