Templated linked list: error on passing reference.

Started by
1 comment, last by SticksandStones 17 years, 9 months ago
Ok, I'm trying to implament a linked list for the heck of it. So, after coming up with a bit of code, I compiled it and ran it to get what I guess is Windows XP version of an illegal error: "Please send this information to Microsoft". I ran Visual C++'s debugger and found out that the error is in this code:

#include "stdafx.h"
#include <iostream>
#include "mylinkedlist.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a = 1;
	mylinkedlist<int> mll;
	mll.push(&a);
	std::cout<<mll.getdata();
	int b;
	std::cin>>b;
	return 0;
}

on the line: mll.push(&a); Here is the function for mylinkedlist::push:

	T* push(T* value)
	{
		if(this->head == NULL)
		{
			this->currentnode = this->head;
			return this->head->data = value;
		}
		else
		{
			this->currentnode->next->data = value;
			this->currentnode = this->currentnode->next;
			return this->currentnode->data;
		}
	};

Any idea of what could be the problem? Here is the full definition of the class, if it is needed:

template <class T> struct node;
template <class T> class mylinkedlist
{
public:
	//T* assign_head(T* value){return this->head->data = value;};
	//T* addlink(T* value){return this->currentnode->next->data = value};
	T getdata(){return (*this->currentnode->data);};
	T* push(T* value)
	{
		if(this->head == NULL)
		{
			this->currentnode = this->head;
			return this->head->data = value;
		}
		else
		{
			this->currentnode->next->data = value;
			this->currentnode = this->currentnode->next;
			return this->currentnode->data;
		}
	};
	mylinkedlist(){this->currentnode = this->head;};
	~mylinkedlist(){};
private:
	bool start;
	node<T>* head;
	node<T>* currentnode;
};

template <class T> struct node
{
	T* data;
	node<T>* next;
};

Any help is appreciated. Update: I've narrowed down the problem: it is either the testing of this->head == NULL, or something is wrong in the "else" statement.
hippopotomonstrosesquippedaliophobia- the fear of big words
Advertisement
You might want to:


  1. Initialize this->head.
  2. Check for NULL before any access to this->currentnode members.
  3. Check the values of the variables in the debugger when the thing crashes.
Wow, I'm an idiot. I forgot to actually declare all the nodes. Thanks ToohrVyk.
hippopotomonstrosesquippedaliophobia- the fear of big words

This topic is closed to new replies.

Advertisement