I am using visual studio 2019 and _CrtDumpMemoryLeaks(); and I get the following message every time
Detected memory leaks!
Dumping objects ->
{160} normal block at 0x007D25A0, 8 bytes long.
Data: < > 04 00 00 00 00 00 00 00
{159} normal block at 0x007D21B0, 8 bytes long.
Data: < %} > 03 00 00 00 A0 25 7D 00
{158} normal block at 0x007D2290, 8 bytes long.
Data: < !} > 02 00 00 00 B0 21 7D 00
{157} normal block at 0x007D2258, 8 bytes long.
Data: < "} > 01 00 00 00 90 22 7D 00
Object dump complete.
The code:
main
#define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #include <iostream> #include "SingleLinkedList.h" int main() { s_list::SingleLinkedList list; list.InsertEnd(1); list.InsertEnd(2); list.InsertEnd(3); list.InsertEnd(4); list.Print(); _CrtDumpMemoryLeaks(); }
SingleLinkedList.h
#pragma once namespace s_list { struct Node { int data; Node* next; }; class SingleLinkedList { private: Node* head, *tail; public: SingleLinkedList(); ~SingleLinkedList(); void InsertEnd(int value); void InsertEnd(Node* node); void Print(); }; }
SingleLinkedList.cpp
#include "SingleLinkedList.h" #include <iostream> using namespace s_list; using namespace std; SingleLinkedList::SingleLinkedList() { head = NULL; tail = NULL; } SingleLinkedList::~SingleLinkedList() { Node* iterator = head, *next; while (iterator != NULL) { next = iterator->next; delete iterator; iterator = next; } } void SingleLinkedList::InsertEnd(int val) { Node* newNode = new Node; newNode->data = val; newNode->next = NULL; if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } }
I think the issue lies in the destructor, and I also tried freeing the memory with free(iterator); but it produces the same result. I scrapped the unrelated part from the code, I hope it helps. And I also looked at other questions related to this issue, but I could not find anything that helped.