Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked List output crash

My program hangs when outputting contents of my linked list. I can't change the header, only the cpp file.

playlist.h:

class PlayList {
    private:

    struct SongNode {
        Song data;
        SongNode* next;
        SongNode (const Song& s, SongNode* nxt = 0)
          : data(s), next(nxt)
        {}
    };

    friend std::ostream& operator<< (std::ostream& out, const PlayList& s);

    SongNode* first; // head of a list of songs, ordered by title, then artist
    //Snip...

    inline
    std::ostream& operator<< (std::ostream& out, const PlayList& pl)
    {
        for (PlayList::SongNode* current = pl.first; current != 0; current = current->next)
            out << current->data << std::endl;
        return out;
    }

playlist.cpp

using namespace std;



PlayList::PlayList()
    : totalTime(0,0,0)
{
}


void PlayList::operator+= (const Song& song)
{
    SongNode* newNode = new SongNode(song, first);
    first = newNode;
}

When outputting the list all of the data that is supposed to print, does print, but then the program hangs.

like image 992
mcudm001 Avatar asked Dec 27 '22 10:12

mcudm001


1 Answers

In the constructor of class PlayList, you need to initialise first:

public:
    PlayList() : first(NULL) {}

Otherwise, in your operator<<, you reach the end of the list and instead of encountering NULL, you just get a junk pointer.

like image 113
Anthony Avatar answered Jan 12 '23 14:01

Anthony