getting error “terminate called after throwing an instance of ‘std::bad_alloc’ what(): std::bad_alloc”

Note: I am posting the answer here so that one does not have to go through the comments in order to find it.

In the function “addSong” from artist.cpp:

void Artist::addSong(Song *song)
{
    the_songs.push_back(song);
    song->artist(*this); // line I will be referencing
}

You are passing the object’s “this” pointer. Every object has its own “this” pointer which gives access to its own memory address. Learn more here: https://www.tutorialspoint.com/cplusplus/cpp_this_pointer.htm

However in the function “artist” from song.cpp:

void Song::artist(Artist artist)
{
    Artist artistou = artist;
}

Side note: Please use setters and getters (Encapsulation) in this scenario. I.e. void set_artist(…) and Artist get_artist().

The parameter does not reflect you passing in a pointer to the memory address of the object. Also, since artistou is declared and defined locally inside of this function, once the program leaves the scope of this function, so will this variables life leave from your computers memory. This variable should be defined in song.h as:

Artist *artistou = new Artist();

and then deleted[] from memory once no longer used as to avoid memory leaks.

Overall, please review some good coding practices on C++. As you said you are new, I am going to drop some links to some important topics that I feel you could benefit from learning.

Inheritance: https://en.cppreference.com/book/intro/inheritance

Encapsulation and Getters and Setters: https://www.w3schools.com/cpp/cpp_encapsulation.asp

Dynamic Memory Management: https://en.cppreference.com/w/cpp/memory

I hope this helped!

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top