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

===============>>#1 票数: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 
{ ... }

我并不是说分段错误是由此引起的,我只是说这段代码是可疑的。

  ask by SaigonWhore translate from so

未解决问题?本站智能推荐: