" bad_alloc的"方法调用期间抛出的异常

时间:2015-04-13 16:35:05

标签: c++ pointers dynamic-memory-allocation bad-alloc

我已经搜索到了这个问题的解决方案,并且无法找到问题,所以我只是求问。我的程序是一个迷宫游戏,包含许多不同的房间,每个房间都使用指针链接到一个或多个相邻的房间。玩家从一个房间走到另一个房间,直到他们找到出口。

当程序在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
}

1 个答案:

答案 0 :(得分:2)

您的问题是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);

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