Memory Leak with linked lists

I have a function called del() that deletes all the nodes in a linked list. If I declare a String called a and call a.del(); in main and leave my destructor empty there are no memory leaks. However if I call del in my destructor there are memory leaks. Example with del() in main:

1
2
3
4
5
6
 int main(){
	myString a("I am A");
	a.del();a
        _CrtDumpMemoryLeaks();
	return 0;
} // I leave my destructor empty and there are no memory leaks 


1
2
3
4
5
int main(){
	myString a("I am A");
        _CrtDumpMemoryLeaks();
	return 0;
} // I call del() in my destructor and this gives me memory leaks 


1
2
3
4
5
6
7
8
9
10
11
12
void myString::del(){
	ListNode* temp = head;
	while (temp != nullptr){
		ListNode *del = temp;
		temp = temp->next;
		delete del;
	}
}

myString::~myString(){
	del();
}
Last edited on
1
2
3
4
5
6
7
8
void myString::del() {
	ListNode* temp = head;
	while (temp) {
		ListNode *del = temp;
		temp = temp->next;
		delete del;  // object delete, not array delete
	}
}
I actually just figured it out. I think I was calling _CrtDumpMemoryLeaks(); before my the destructor was called. So it would list all the memory leaks, then my destructor would delete the objects. So I put _CrtDumpMemoryLeaks(); before del(); in my destructor to see if it would list the memory leaks and it did. I put _CrtDumpMemoryLeaks(); after del() in my destructor and it didn't list any memory leaks. Thanks for the help though!
Topic archived. No new replies allowed.