gpt4 book ai didi

c++ - "bad_alloc"方法调用时抛出异常

转载 作者:行者123 更新时间:2023-11-28 02:28:51 27 4
gpt4 key购买 nike

我四处寻找这个问题的解决方案,但找不到,所以我只好问问。我的程序是一个迷宫游戏,其中包含许多不同的房间,每个房间都使用指针链接到一个或多个相邻的房间。玩家从一个房间导航到另一个房间,直到找到导出。

当程序到达我的 Turn() 函数中的这一行时,对 getName() 的调用将引发“bad_alloc”异常:

cout << "You are currently in " << current->getName()
//that's not the entire line but it's the important bit

getName() 所做的只是将房间名称作为字符串返回。 currentRoom* 类型的指针,指向用户当前所在的房间。我猜这个指针就是问题所在,但很明显在 main() 中定义:

int main()
{
//first I create a Maze object to hold important variables, and then the nineteen rooms
Maze maze = Maze();
Room room1 = Room("Room A");
Room room2 = Room("Room B");
Room room3 = Room("Room C");
//and so on...
Room empty = Room(""); //used as a placeholder for rooms with less than five adjacent rooms

//set the rooms adjacent to each room
room1.SetAdjacent(room2, room3, room4, empty, empty);
room2.SetAdjacent(room1, room5, room6, empty, empty);
room3.SetAdjacent(room1, room6, room7, room15, empty);
//and so on...

//this explicitly sets the "current" pointer to point to room1:
maze.SetCurrent(&room1);

cout << "Welcome to The Maze Game. Can you find your way out?" << endl;
system("pause");

do
{
maze.Turn();
if (maze.GetWinStatus() == true)
{
cout << "You have reached the exit! Congratulations!" << endl;
}
system("pause");
} while (maze.GetWinStatus() == false); //if the player hasn't moved to the exit, then it loops round for another turn

return 0;
}

所以我不明白为什么它会抛出这个异常。如果您想查看任何其他代码,请询问,我很乐意将其张贴在这里。

编辑 2:这是整个 Room 类,按照要求:

class Room
{
private:
string roomName;
Room* adjacentRooms[5];
public:
Room(string name);
string getName();
void SetAdjacent(Room adj1, Room adj2, Room adj3, Room adj4, Room adj5);
Room* GetAdjacent(int room);
};

Room::Room(string name)
{
roomName = name;
}

string Room::getName() //this is the bit that makes it crash
{
return roomName;
}

void Room::SetAdjacent(Room adj1, Room adj2, Room adj3, Room adj4, Room adj5)
{ //sets which rooms are adjacent to the room this function is called from
adjacentRooms[0] = &adj1;
adjacentRooms[1] = &adj2;
adjacentRooms[2] = &adj3;
adjacentRooms[3] = &adj4;
adjacentRooms[4] = &adj5;
}

Room* Room::GetAdjacent(int room)
{ //returns one of the five adjacent rooms. Numbers 1-5 are used as inputs for user convenience
return adjacentRooms[room - 1]; //the number is lowered by 1 to get the right room in the array
}

最佳答案

您的问题是您的 SetAdjacent 方法:

void SetAdjacent(Room adj1, Room adj2, Room adj3, Room adj4, Room adj5);

应通过引用获取其参数:

void SetAdjacent(Room& adj1, Room& adj2, Room& adj3, Room& adj4, Room& adj5);

发生的事情是您正在获取函数返回后超出范围的临时地址。对该内存的后续访问是未定义的行为。

关于c++ - "bad_alloc"方法调用时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610496/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com