Destructor not working

closed account (Ey80oG1T)
So I'm making a SLL class, however, it appears that I have some memory leaks. Here's the code that's causing problems:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// used to detect memory leaks in Visual Studio
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

class sll
{
private:
	struct Node
	{
		int val;
		Node* next;
	};

private:
	Node* head;

public:
	sll()
		: head(nullptr) {}

	~sll()
	{
		Node* node_ptr = head;
		while (head != nullptr)
		{
			node_ptr = node_ptr->next;
			delete head;
			head = node_ptr;
		}
	}

public:
	void insert_back(int val)
	{
		if (head == nullptr)
		{
			head = new Node{ val, nullptr };
			return;
		}

		Node* node_ptr = head;
		while (node_ptr->next != nullptr)
			node_ptr = node_ptr->next;

		node_ptr->next = new Node{ val, node_ptr->next };
	}
};

int main()
{
	sll list;
	list.insert_back(1);
	list.insert_back(2);
	list.insert_back(3);

        // logs memory leaks for Visual Studio
	_CrtDumpMemoryLeaks();
}


When I run the code, it tells me I have three leaks, one for each insert. But why is this? How did I mess up on my destructor?

Also, yes, it's better to use smart pointers, but I'm using raw pointers for now.
The destructor has yet to run at line 62. list is still in scope.
Yeah, just put braces around lines 56 to 59.

And if you want to be able to append to the back of the list you should maintain a tail pointer.
Topic archived. No new replies allowed.