I'm assisting a friend with an assignment, an implementation of a linked list, though my C++ skills are rusty at best these days.
There's a few structs
struct Song{
int id;
string name;
string singerName;
};
struct SongNode {
Song sg;
SongNode *previousNode;
SongNode *nextNode;
};
struct SongDoublyLinkedList{
SongNode *firstElement;
};
And this short piece that runs in main
SongDoublyLinkedList* list = new SongDoublyLinkedList();
SongNode* song1 = new SongNode();
song1->sg.id = 1;
song1->sg.name = "All Night";
song1->sg.singerName = "Parov Stelar";
addSong(list, song1);
SongNode* song2 = new SongNode();
song2->sg.id = 2;
song2->sg.name = "Song 2";
song2->sg.singerName = "Blur";
addSong(list, song2);
Then the two functions
SongNode *getLastSong(SongDoublyLinkedList *songList)
{
if (songList->firstElement == NULL) return NULL;
SongNode currentElement = *(songList->firstElement);
while (currentElement.nextNode != NULL)
{
currentElement = *(currentElement.nextNode);
}
return ¤tElement;
}
void addSong(SongDoublyLinkedList *songList, SongNode *songNd)
{
songNd->nextNode = NULL;
songNd->previousNode = NULL;
SongNode* lastNode = getLastSong(songList);
if (lastNode == NULL) songList->firstElement = songNd;
else lastNode->nextNode = songNd;
}
The issue is in return ¤tElement;
in getLastSong
when adding the second element, but I don't understand what the issue is. It's almost acting like the memory is being free, but isn't. This initially made me think I was returning the wrong value, but I ran it through the Visual Studio debugger and the pointer seems to work fine within the getLastSong
function, but not outside of its scope.
Value Good:
Value Bad:
Also, if I try to dereference the bad `lastNode' then a get some manner of memory access error, so it really seems like I'm sending a bad value.
I assume I'm missing something silly (or more likely, I've forgotten an element of C++ after having worked with C# for years), why isn't this working the way I expect?