Fresh out of my first CS class, I wanted to get more practice with recursive memory allocation, so I decided to make a little game known as the "Recursive Dungeon." It simply allows users to roam through an infinite dungeon by recursively generating a new "room" every time a player enters an empty (NULL) room.
The new room is then saved, and can be accessed by...
- Going down the exact same path that was used when entering the room
- If you leave the room, retracing your steps back to the same room
*The program doesn't use cycles (at least, I don't think it does). I'm unfamiliar with the concept of a cycle as well as how to use it.
The problem I'm running into is when I try to clean up all the recursively-allocated memory (the "rooms"), I receive the classic error "segmentation fault: core dumped".
Below is my structure "room":
struct room
{//begin struct
room* backward;
room* left;
room* forward;
room* right;
string desc;
room() { //begin
backward = NULL;
left = NULL;
forward = NULL;
right = NULL;
/*End*/}
/*End struct*/};
Each "room" has other rooms connected to it (left/right/forward/backward). The user starts in an empty room pointer "startingpoint", and may go in any of the above directions. Upon attempting to enter an empty (NULL) room, a new room is randomly generated for the user enter into.
Once the player is satisfied exploring, I attempt to clean up the allocated memory using an array that stores all the rooms before ending the program. Instead, it causes the segmentation fault. Here is the code:
void ClearAllocatedMemory(room* aRoom, room** roomArray, int& raIndex) {
for(short i=0; i<raIndex; i++) {//begin for
delete roomArray[i];
/*End for*/}
delete[] roomArray;
/*End func*/}
Here is the code that makes my array and defines its first (0th) index:
room** roomArray;
int raIndex = 0;
room* startingpoint = new room();
roomArray[0] = startingpoint;
And here is the code that adds in new rooms to the roomArray index:
room* GenRoom(room** roomArray, int& raIndex) {
room* newroom = new room();
newroom->desc = GenRoomDesc( rand()%12 + 1 );
raIndex++;
roomArray[raIndex] = newroom;
return newroom;
}