I've been working on this project for a while now and it's completely done. Except that when I run it in Linux I get a segmentation fault. I'm a beginner with C++, and while I understand that a segmentation fault has to do with trying to access already freed memory, I don't understand where I'm going wrong with the memory I am trying to access. Below is the function where I am having the problem. I marked the line of code that I think is causing the problem with a comment. Please let me know if you see what I am doing wrong, I'd really appreciate it!
int TsuPod::SortSongList(string x, string y, int z)
{
Song InsertSong(x, y, z); //creates song object
node* newNode = new node; //creates new node
//initializes all the node's values
newNode->title = InsertSong.GetTitle();
newNode->artist = InsertSong.GetArtist();
newNode->size = InsertSong.GetSize();
//case 1 - Inserting into an empty list
if(head == NULL)
{
head = newNode;
}
else
{
curr = head;
prev = NULL;
//Traverse
while(curr != NULL)
{
if(curr->title >= newNode->title)
{
break;
}
else
{
prev = curr;
curr = curr->next;
}
}
}
if(curr == head)
{
//case 2 - Insert at head
newNode->next = head;
head = newNode; //Causing Segmentation fault?
}
else
{
//case 3 - Insert after the head
newNode->next = curr;
prev->next = newNode;
}
remainingMem = remainingMem - newNode->size;
slots++;
return 1;
}
headsomewhere else in your code? By calling other functions somewhere else?node. As written there is no verification that it initializes thenextmember to NULL, which would be catastrophic to this algorithm (which can be made considerably simpler regardless). It would also make your algorithm much cleaner if all the InsertSong stuff were done in the constructor fornode, thereby eliminating the clutter here.