Skip to content

Commit 8bde3ea

Browse files
fix: remove memory leak in sublist_search.cpp (TheAlgorithms#2541)
Co-authored-by: realstealthninja <[email protected]>
1 parent 7fc338d commit 8bde3ea

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

search/sublist_search.cpp

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,20 @@ Node *makeLinkedList(const std::vector<uint64_t> &data) {
9090
return head;
9191
}
9292

93+
/*
94+
* @brief This function dealocates memory related to the given list
95+
* It recursively deletes all of the nodes of the input list.
96+
* @param room the root/head of the input list
97+
* @warning Plese note that the memory for each node has to be alocated using
98+
* new.
99+
*/
100+
void deleteList(Node *const root) {
101+
if (root != NULL) {
102+
deleteList(root->next);
103+
delete root;
104+
}
105+
}
106+
93107
/**
94108
* @brief Main searching function
95109
* @param sublist A linked list which is supposed to be searched in mainList.
@@ -217,8 +231,8 @@ class TestCases {
217231
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
218232
"~");
219233

220-
delete (sublistLL);
221-
delete (mainlistLL);
234+
deleteList(mainlistLL);
235+
deleteList(sublistLL);
222236
}
223237

224238
/**
@@ -270,6 +284,9 @@ class TestCases {
270284
log("[PASS] : TEST CASE 2 PASS!");
271285
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
272286
"~");
287+
288+
deleteList(mainlistLL);
289+
deleteList(sublistLL);
273290
}
274291

275292
/**
@@ -318,6 +335,9 @@ class TestCases {
318335
log("[PASS] : TEST CASE 3 PASS!");
319336
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
320337
"~");
338+
339+
deleteList(mainlistLL);
340+
deleteList(sublistLL);
321341
}
322342
};
323343

@@ -366,5 +386,8 @@ int main(int argc, char *argv[]) {
366386
} else {
367387
std::cout << "[FALSE] - sublist NOT found in main list\n";
368388
}
389+
390+
deleteList(mainlistLL);
391+
deleteList(sublistLL);
369392
return 0;
370393
}

0 commit comments

Comments
 (0)