I am trying to read in a data file (a maze), of which I seem to have coded myself a seg fault, I admit that I was sick for the lecture in my college about dynamic allocation, and have searched for my issue throughly, to no avail. Here is my snippet of code:
void MazeClass::ReadMaze(ifstream& mazedata) {
mazedata >> row >> column; // Pulls the size from the file
GetExit(mazedata); // Does the same for above, just for the Exit (Required in Class)
GetEntrance(mazedata); // Does the same, just for the entrance (Required in Class)
maze = new char*[row]; // First array of pointers for 2d array
for (unsigned i; i<row;i++)
{ // Creates the second set of arrays
maze[i]=new char[column];
}
for (int y=0;y<column;y++)
{ // Keeping the maze inside boundries (step 1)
for (int x=0;x<row;x++) // (Step 2)
{
maze[x][y]=mazedata.get(); // <--- Here is where my Seg Fault happens.
}
}
}
Here is what gdb tells me:
Program received signal SIGSEGV, Segmentation fault. 0x08048fe9 in MazeClass::ReadMaze (this=0xbffff524, mazedata=...) at MazeClass.cpp:36 36 maze[x][y]=mazedata.get();
Thank you ahead of time for all of the help.
Now that my code is fixed by a silly mistake, I am now able to move on to the next problem:
(gdb) run
Starting program: /home/athetius/projects/code/netbeans/OLA4/a.out
Please Enter Data Filename: MyMaze2.dat
**************12142*********** ***12142*
* 12142***** * * 12142 *
* 12142 ************ 12142***
*** * 12142 ****12142****
* 12142 12142 *
* ****12142***** ** * 12142 *
* 12142 * 12142 * * *
* 12142 *******12142*** *
* 12142* ** ***12142*********
* 12142 12142
* 12142 *************12142*** *
* 12142 12142 ***** **
**12142************* 12142 * *
*12142 ******* 12142 **
12142***************12142
Program exited normally.
With the output of: view MyMaze2.dat being:
************************* ****
* ***** * * *
* ************ ***
*** * ********
* *
* ********* ** * *
* * * * *
* ********** *
* * 开发者_如何学Python ** ************
*
* **************** *
* ***** **
*************** * *
* ******* **
******************************
In the line for (unsigned i; i<row;i++)
which starts your first for
loop, you don't initialize i
. Try unsigned i=0;
. That may not fix everything, but its a start :)
The actual problem seems to be a few lines earlier in the code
for (unsigned i; i<row;i++)
What is the initial value for i here? Nothing?
精彩评论