I'm supposed to use dynamic character arrays (cstring) to allocate memory for the full list and also for the individual names. These occur in two different classes.
I've been debugging with gdb in Linux and using valgrind to try to find the memory leaks, but as far as I can tell I'm doing everything right by using the delete operator.
These are my headers for the classes:
class Song
{
private:
char *songName;
char *artistName;
int minutes;
int seconds;
char *albumName;
}
class SongList
{
private:
Song *list;
int size;
}
Here are the destructors:
Song::~Song()
{
if (songName)
{
delete [] songName;
songName = NULL;
}
if (artistName)
{
delete [] artistName;
artistName = NULL;
}
if (albumName)
{
delete [] albumName;
albumName = NULL;
}
}
SongList::~SongList()
{
if(list)
{
delete [] list;
list = NULL;
}
}
Valgrind is showing me 18 bytes lost in 3 blocks. I'm also getting Invalid free()... messages, but I believe that's unrelated to memory leaks?
Thanks!
-Edit-
Here is the code where I allocate memory.
Song::Song()
{
songName = new char[13];
artistName = new char[15];
albumName = new char[14];
strcpy(songName, "No song name");
strcpy(artistName, "No artist name");
minutes = 0;
seconds = 0;
strcpy(albumName, "No album name");
}
SongList::SongList(char fileName[])
{
list = new Song[CAP];
}
The memory is freed in the class destructors. When the SongList class calls Song methods, it deallocates the memory allocated by the default constructor in class Song and reallocates it based on how many bytes it needs to store the new information. Like this:
void Song::setName(char newName[])
{
if (songName)
{
delete [] songName;
songName = NULL;
}
songName = new char[strlen(newName) + 1];
strcpy(songName, newName);
}
Here is a link to screenshots of the valgrind info. I'm using putty so I don't really know how to get it out of the console otherwise.
https://i.stack.imgur.com/EWIq1.jpg
Sorry, I'm so new to this that I don't really know what parts of my code will be relevant to someone trying to help. Thanks for the help!