Reputation: 12327
In my project there is a level class which can have rooms set
class Level
{
public:
Room * exit;
Room * position;
Level(Room setExit, Room newPosition);
~Level();
void showPosition();
};
realative in .h file
Level::Level(Room setExit, Room setPosition)
{
exit = &setExit;
position = &setPosition;
}
void Level::showPosition(){
position->printInfo();
}
Room class.
class Room
{
string title;
string info;
Room(string titleInput, string infoInput) :info(infoInput), title(titleInput){};
void printInfo();
.h function printinfo
void Room::printInfo(){
cout << title << endl;
}
My Main program that runs.
Room room1("Dungeon", "This is a dangerous room.");
room1.printInfo();
Level lvl1(room1, room1);
This works fine but when i call.
lvl1.showPosition();
I get a bad alloc. So i know the error is in Level function showPosition. But why do i get a bad_alloc error?
Upvotes: 0
Views: 99
Reputation: 409176
The Level
constructor will soner or later lead you to undefined behavior:
Level::Level(Room setExit, Room setPosition)
{
exit = &setExit;
position = &setPosition;
}
The arguments setExit
and setPosition
are just like normal local variables, in other words they go out of scope (and get destructed) once the function returns. That leaves you with two stray pointers, pointing to now destructed objects (and memory that can be reused). Using these pointers is what will give you UB.
If you need to use pointers, pass the pointers as arguments, and make sure that the object they point to have a lifetime the same (or greater) than the Level
object.
Potentially, you could use std::shared_ptr
here.
Upvotes: 4
Reputation: 96266
Level::Level(Room setExit, Room setPosition)
{
exit = &setExit;
position = &setPosition;
}
The Room
is passed by value. You store the address of the temporary that will go out of scope.
Upvotes: 0