Advertisement

Odd pointer deletion errors (lots of source)

Started by March 02, 2001 10:16 AM
-1 comments, last by rileyriley 23 years, 11 months ago
I''m having a very frustrating problem with my LinkedList class. The problem occurs in the removeItem method. I go through the entire process of updating the list, which works successfully, but when it comes time to actually delete the appropriate node, I get an unmapped memory exception. I''ve checked the pointer with various memory tools and it has always been valid and pointed to a valid, initiated object. The following is the main function:
  #include <iostream.h>
#include "linkedlist.h"
#include "linkedlist.cpp"

int main()
{
	LinkedList <int> test;
	
	int var1 = 1, var2 = 2, var3 = 3, var4 = 4;
	
	test.addItem(&var1);
	test.addItem(&var2);
	test.addItem(&var3);
	test.addItem(&var4);
	
	cout << "Hello World, this is CodeWarrior!" << endl;
	
	test.removeItem(&var2);
	
	cout << "AHASDKJHFLSKJFH" << flush;
	return 0;
}  
this is the class declaration (linkedlist.h)
  template <class itemType>

struct LLNode
{
	LLNode * prev;
	LLNode * next;
	itemType * item;
};

template <class itemType>

class LinkedList
{

public:
	LLNode <itemType> * theList;

	LinkedList();
	void addItem(itemType * item);
	void removeItem(itemType * item);
	~LinkedList();
};  
and finally the function that causes the error:
  template <class itemType>
void LinkedList<itemType>::removeItem(itemType * itemToBeRemoved)
{
	LLNode <itemType> * temp = theList;
	while (temp->item != itemToBeRemoved && temp != 0)
	{
		temp = temp->next;
	}
	
	if (temp != 0) //if we did indeed find the item

	{
		if (temp->prev != 0)
			temp->prev->next = temp->next;  //set the previous item to skip the current item

		if (temp->next != 0)
			temp->next->prev = temp->prev;
		
		if (temp == theList)    //it''d be a shame to delete the first pointer

			theList = temp->next;  //so we do some quick backup

		
		delete (temp->item);  //delete the item space  THIS IS THE LINE THAT CAUSES THE EXCEPTION

		delete temp;	//delete the node

		
	}
}  
again, I have checked _all_ pointers to make sure that they are valid and initiated, and checked the list to make sure it ends in NULLs, etc.. This is extremely frustrating... it causes the exception even before it steps into assembly code (using the code warrior debugger). Thanks for any help :/
--Riley

This topic is closed to new replies.

Advertisement