4

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

You forgot to initialize first in the constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.