gpt4 book ai didi

c++ - 使用链表插入排序的段错误

转载 作者:行者123 更新时间:2023-11-28 06:55:55 25 4
gpt4 key购买 nike

我已经在这个项目上工作了一段时间,现在已经完全完成了。除了当我在 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;
}

最佳答案

首先让我印象深刻的是:

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
{ ... }

我并不是说段错误是由此引起的,我只是说这段代码有问题。

关于c++ - 使用链表插入排序的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23176910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com