From 0659c54e77a82c982b8b3b8b8f57cc59fe3d2fba Mon Sep 17 00:00:00 2001 From: Gonglja <39959756+Gonglja@users.noreply.github.com> Date: Mon, 20 Mar 2023 21:17:19 +0800 Subject: [PATCH] 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 --- codes/cpp/include/PrintUtil.hpp | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/codes/cpp/include/PrintUtil.hpp b/codes/cpp/include/PrintUtil.hpp index e54926251..a76f7a80a 100644 --- a/codes/cpp/include/PrintUtil.hpp +++ b/codes/cpp/include/PrintUtil.hpp @@ -99,10 +99,13 @@ class PrintUtil { static void printArray(T* arr, int n) { cout << "["; - for (size_t i = 0; i < n - 1; i++) { + for (int i = 0; i < n - 1; 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 = " "; - Trunk *trunk = new Trunk(prev, prev_str); + Trunk trunk(prev, prev_str); - printTree(root->right, trunk, true); + printTree(root->right, &trunk, true); if (!prev) { - trunk->str = "———"; + trunk.str = "———"; } else if (isLeft) { - trunk->str = "/———"; + trunk.str = "/———"; prev_str = " |"; } else { - trunk->str = "\\———"; + trunk.str = "\\———"; prev->str = prev_str; } - showTrunks(trunk); + showTrunks(&trunk); cout << " " << root->val << endl; if (prev) { prev->str = prev_str; } - trunk->str = " |"; + trunk.str = " |"; - printTree(root->left, trunk, false); + printTree(root->left, &trunk, false); } /**