I'm getting a segmentation fault at this line. So far, my program has classes. A blahpod with class of songs in them. Then there is the node class. I call the operator= which is supposed to put one pod into another. It looks like so

bobcatPod bp2( bp1 );

That accesses the functions in my bobcatPod.cpp file.

bobcatPod::bobcatPod(const bobcatPod & rhs)
{
(*this) = rhs;
}

Which in turn accesses

bobcatPod & bobcatPod::operator=(const bobcatPod & rhs)
{
	while(firstNode != NULL)
	{
		removeSong(firstNode->data.getTitle(), firstNode->data.getArtist());
	}
	node *endOfList;
	for(node *ptr=rhs.firstNode; ptr!=NULL; ptr = ptr->next)
	{
		node *temp = new node;
		temp->data = ptr->data;
		temp->next = NULL;
		if(firstNode == NULL)
			{
			firstNode = temp;
			endOfList = temp;
			}
		else
		{
			endOfList->next = temp;
			endOfList = temp;
		}
	}
}

So the segmentation fault (I think) involves either the while loop or the remove song in the while loop. Here is what the remove function looks like

void bobcatPod::removeSong( string title, string artist)
{
	if(firstNode == NULL)
		return;
	if(title ==firstNode->data.getTitle() && artist == firstNode->data.getArtist())
	{
		node *delptr=firstNode;
		if(firstNode->next != NULL)
			{
			firstNode = firstNode->next;	
			setStorageSize(-1*delptr->data.getSize());
			delete delptr;
			return;
			}
		else
			{
			delete firstNode;
			delete delptr;
			return;
			}
	}		

	for(node *temp=firstNode; temp!=NULL && temp->next!=NULL; temp=temp->next)
	{
	if(title == temp->next->data.getTitle() && artist == temp->next->data.getArtist())
		{
		node *delptr=temp->next;
		temp->next = delptr->next;
		setStorageSize(-1*delptr->data.getSize());
		delete delptr;
		}
	}
}

Okay, so I don't really see the problem. Anyone have any ideas why I'm getting a segfault? I thought I knew this stuff, but I've spent 3 hours looking for it and can't find it. Please help... If you can draw a pretty picture in paint showing which nodes the pointers are pointing too, I'd be super happy :D

Thank you!
~Rimo

It looks to be this line

for(node *temp=firstNode; temp!=NULL && temp->next!=NULL; temp=temp->next)

Lets say you removed the one and only node in your list. In the code you hit the else part and do a 'delete firstNode', however you are not setting the pointer to null. Then you come to this line and assign the address in firstNode(which is still there in firstNode) to temp and then try and access temp which gives the segmentation.

You could set firstNode to null after you delete it but generally you should try and avoid situations where you use a pointer after a possible deletion.

I tried that but it didn't really work. For some reason, I still get the segmentation fault. I'm absolutely clueless, sorry.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.