I made a Node class and tried to implement a simple tree structure using C++. I tested the code, visual studio was able to compile and output the expected results. However, when I tried Dr Memory to check memory leak, Dr Memory always crash at certain points, including: 1) in the Node class constructor "col = vec[0].size()" 2) in the distance function "col = vec[0].size()"
If I kept those lines, visual studio can compile and output the right thing, however, Dr Memory crash... If I commented those lines, Dr Memory works... So I am quite confused what part went wrong, is the nodes on the heap? or the vector? or Dr Memory... Thank you
// node class
class Node {
public:
vector<vector<int>> board;
int row;
int col;
Node(vector<vector<int>> &vec): board(vec) {
row = vec.size();
col = vec[0].size();
}
Node(Node *&node): board(node->board) {}
};
// calculate distance
int distance(v2_i &vec) {
int ans = 0;
int row = vec.size();
int col = vec[0].size();
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++) ans += abs(vec[i][j]-(i*row+j+1));
}
return ans;
}
// main function
int main() {
vector<vector<int>> startBoard = input_txt();
Node *node_1 = new Node(startBoard);
Node *node_2 = new Node(node_1);
cout << distance(node_2->board) << endl;
delete node_1;
delete node_2;
return EXIT_SUCCESS;
}