access violation when deleting pointer

I tried to delete the pointer i created but it shows "Access violation reading location 0x00000020."

Did i put the delete in the wrong place? any help is appreciated. thanks!

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
  void linkedlist<itemtype>::insertnode(int index, itemtype data)
{
	if (index < 0 || index > linkedlist::size())
	{
		return;
	}
	else
	{
		node* temp1 = new node();
		temp1->data = data;
		temp1->next = NULL;

		if (index == 0)
		{
			count++;
			temp1->next = head;
			head = temp1;
			return;
			
		}

		else
		{
			count++;
			node* temp2 = head;
			for (int i = -1; i < index - 2; i++)
			{
				temp2 = temp2->next;
			}
			temp1->next = temp2->next;
			temp2->next = temp1;
			
		}
		delete temp1;
	}
	
}
Why are you deleting it when you've added references to it in several places?
@LB : to avoid memory leak? or am i not supposed to delete it?
You delete it when you are 100% done with that particular memory address. Which probably will be in your destructor. [edit] or if you have some sort of delete/erase function.[/edit]
Last edited on
You don't have a memory leak if you can still reference the data!
Topic archived. No new replies allowed.