Fix memory leaks (#433)

* fix(codes/cpp): Memory leak fix: the space was not freed when pop removed the element.

* fix(codes/cpp): Fix access error when printArray(arr, 0)

* fix(codes/cpp): Fix memory leaks: replace pointers with local variables, no need to manage memory
This commit is contained in:
Gonglja 2023-03-20 21:17:19 +08:00 committed by GitHub
parent c837882dbd
commit 0659c54e77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -99,10 +99,13 @@ class PrintUtil {
static void printArray(T* arr, int n) static void printArray(T* arr, int n)
{ {
cout << "["; cout << "[";
for (size_t i = 0; i < n - 1; i++) { for (int i = 0; i < n - 1; i++) {
cout << arr[i] << ", "; cout << arr[i] << ", ";
} }
cout << arr[n - 1] << "]" << '\n'; if (n>=1)
cout << arr[n - 1] << "]" << endl;
else
cout << "]" << endl;
} }
/** /**
@ -206,31 +209,31 @@ class PrintUtil {
} }
string prev_str = " "; string prev_str = " ";
Trunk *trunk = new Trunk(prev, prev_str); Trunk trunk(prev, prev_str);
printTree(root->right, trunk, true); printTree(root->right, &trunk, true);
if (!prev) { if (!prev) {
trunk->str = "———"; trunk.str = "———";
} }
else if (isLeft) { else if (isLeft) {
trunk->str = "/———"; trunk.str = "/———";
prev_str = " |"; prev_str = " |";
} }
else { else {
trunk->str = "\\———"; trunk.str = "\\———";
prev->str = prev_str; prev->str = prev_str;
} }
showTrunks(trunk); showTrunks(&trunk);
cout << " " << root->val << endl; cout << " " << root->val << endl;
if (prev) { if (prev) {
prev->str = prev_str; prev->str = prev_str;
} }
trunk->str = " |"; trunk.str = " |";
printTree(root->left, trunk, false); printTree(root->left, &trunk, false);
} }
/** /**