我已经在这个项目上工作了一段时间而且已经完成了。除了当我在Linux中运行它时,我遇到了分段错误。我是C ++的初学者,虽然我知道分段错误与尝试访问已经释放的内存有关,但我不明白我在尝试访问的内存出错了。以下是我遇到问题的功能。我标记了我认为导致注释问题的代码行。如果你看到我做错了,请告诉我,我真的很感激!
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;
}
答案 0 :(得分:1)
首先引起我注意的是:
if(head == NULL) <--- lets assume that head was null
{
head = newNode; <---- executed
}
else
{ <---- not executed, skipped
curr = head; <---- this is skipped, curr is not assigned to head
prev = NULL;
//Traverse
while(curr != NULL) { ... }
}
if(curr == head) <----- Huh... What is curr right now? When was
curr last set to a value
{ ... }
我并不是说分段错误是由此引起的,我只是说这段代码很可疑。