Linked List Failed

My program freezes when it displays the contents of my linked list. I can not 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 the list is displayed, all the data that should be printed is printed, but then the program freezes.

+4
source share
2 answers

In the constructor of the class PlayList you need to initialize first :

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

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

+6
source

You forgot to initialize first in the constructor.

+4
source

Source: https://habr.com/ru/post/1384236/


All Articles