I have a class:
class Land{
public:
~Land() { if(map != nullptr) Clean(); }
bool Create();
void PrintMap() const;
void Clean();
private:
int rows = 0, columns = 0;
int **map = nullptr;
bool CorrectDimensions() const;
void CreateMap();
bool FillMap();
};
bool Land::Create() {
//
printf("Matrix size:\n");
if(scanf("%d %d", &(this->columns), &(this->rows) ) != 2 || !CorrectDimensions() )
return false;
CreateMap();
printf("Values:\n");
return FillMap();
}
void Land::CreateMap() {
//
this->map = new int*[rows];
for(int column = 0; column < this->rows; column++)
map[column] = new int[this->columns];
}
bool Land::FillMap() {
//
for(int row = 0; row < this->rows; row++) {
for(int column = 0; column < this->columns; column++) {
if( ! scanf("%d", &(this->map[row][column]) ) ) {
return false;
}
}
}
return true;
}
void Land::Clean() {
//
for(int row = 0; row < this->rows; row++)
delete [] this->map[row];
delete [] this->map;
}
And my driver:
int main() {
//
Land l;
if( ! l.Create() ) {
IncorrectInput();
return 1;
}
l.PrintMap(); //prints correct output
}
How I imagine my program should work:
- Default constructor gets called, no need for a custom one.
- Check if the input satisfies the requirements. If not, return
falsethus finishing the program. Memory hasn't been dynamically allocated yet (stays atnullptr), no problem. - If yes, create a 2D array using
calloc(I know I'm mixing C with C++, wanted to use class andvectoris not available). - Fill that 2D array with scanned values. If scanned values aren't ints, return false, thus finishing the program.
- Print the value of that array. Const function.
- Finish the program so destructor is called. Since I don't know if
Create()ended prematurely (beforecalloc) or not, I default initializeint **maptonullptr. If I allocate,mapwon't benullptranymore and will need to be freed. Otherwise, destructor shouldfree, that's whatClean()does. Clean()I followed the practices of dynamic allocation and freeing.callocandfreefollow their reversed patterns. Debugging confirmed that how manycallocs were called, that manyfrees were called.
With all of this, valgrind still reports errors (not reachable, actual errors). Specifically: total heap usage: 184 allocs, 23 frees. What caused this error, what have I missed?
EDIT: Initialized rows and columns members. Changed calloc() with C++ new and delete.