使用iostream和指针获取Seg Fault

时间:2011-03-13 07:23:36

标签: c++

我正在尝试阅读一个数据文件(一个迷宫),其中我似乎自己编写了一个seg错误,我承认我因为我的大学关于动态分配的讲座感到恶心,并且已经搜索了我的彻底发布,无济于事。  这是我的代码片段:

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.
        }
    }

}

这是gdb告诉我的内容:

  

编程接收信号SIGSEGV,分段故障。   在MazeClass.cpp中的MazeClass :: ReadMaze(这= 0xbffff524,mazedata = ...)中的0x08048fe9:36   36迷宫[x] [y] = mazedata.get();

提前感谢您提供所有帮助。

既然我的代码是由一个愚蠢的错误修复的,我现在能够继续讨论下一个问题:

(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.

输出: 查看MyMaze2.dat:

************************* ****
*            ***** *     *   *
*            ************  ***
***   *               ********
*                            *
*    *********   ** *        *
*               *       * *  *
*              **********    *
*     *        ** ************
*                             
*     ****************       *
*                    *****  **
***************   *          *
*       *******             **
******************************

2 个答案:

答案 0 :(得分:5)

在开始第一个for (unsigned i; i<row;i++)循环的行for中,您不会初始化i。试试unsigned i=0;。这可能无法解决所有问题,但这只是一个开始:)

答案 1 :(得分:1)

实际问题似乎是代码中的几行

for (unsigned i; i<row;i++)

我这里的初始价值是多少?什么?