struct pointer, check if null

I am -- for practice's sake -- trying to make some sort of queue system with a simple linked list that have a queue entry structure (T value and next). I try upon adding the first element to see if there's already anyone there, but checking for a Entry* pointer existing has not proven easy.

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
template <class T>
class Queue
{
public:
	void add(T item)
	{
		T* value = &item;
		if(last)
		{
			last->next = new Entry();
			last->next->value = value;
			last = last->next;
		}
		else
		{
			front = new Entry;
			last = front;
		}
	}
private:
	struct Entry
	{
		T* value;
		Entry* next;
	};
	Entry* front;
	Entry* last;
	int* length;
};
int main()
{
	Queue<int> q;
	q.add(32);
	system("pause");
}

The error gotten on runtime is
Unhandled exception at 0x012414fa: 0xC00000005. Access violation writing location 0xccccccc0

I'm pretty clueless here. It seems to go on even though the front* and last* leads to nowhere.
You need to write a constructor for the Queue class. In there, initialize all of your pointers to NULL and that will help tremendously.
you need contractor to set null to your pointer and distructor to free memory
I did so and they were added as usual, but when trying to use a simple peek function (get the next one, but not remove it) I get the magic number CDCDCDCD, which according to Wikipedia means uninitialized heap memory, do you know why? I think the problem lies within the peek() method.

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
template <class T>
class Queue
{
public:
	// Constructor and Destructor
	Queue()
	{
		front = NULL;
		last = NULL;
	}
	void add(T item)
	{
		T* value = &item;
		if(last)
		{
			last->next = new Entry();
			last->next->value = value;
			last = last->next;
		}
		else
		{
			front = new Entry;
			last = front;
		}
	}
	T* peek()
	{
		if(front != NULL)
		{
			return front->value;
		}
		else
		{
			return NULL;
		}
	}
private:
	struct Entry
	{
		T* value;
		Entry* next;
	};
	Entry* front;
	Entry* last;
	int* length;
};
int main()
{
	Queue<int> q;
	int v = 4;
	q.add(v);
	cout << q.peek() << endl;
	system("pause");
}

Trying to return a dereferenced value gives an exception. It's for debugging's sake that I returned the pointer.
Last edited on
When you call add() the first time, last is NULL, so your if statement allocates front, but you didn't assign a value to it.
Okay, now I assigned the value to it -- I should have noticed that really -- and now it returns a large number upon dereferncing in peek(). Why does it do that?
Try making add take a reference to a T instead of by value.
Thank you, it works now.
Topic archived. No new replies allowed.