0

我相信您(专业人士)可以识别我的代码中的错误,我也将不胜感激对我的代码的任何其他评论。

顺便说一句,代码在我运行后崩溃。

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct
{
    int x;
    int y;
}  Location;

typedef struct
{
    bool walkable;
    unsigned char walked; // number of times walked upon
} Cell;

typedef struct
{
    char name[40];  // Name of maze
    Cell **grid;    // 2D array of cells
    int rows;       // Number of rows
    int cols;       // Number of columns
    Location entrance;
} Maze;


Maze *maz_new()
{
    int i = 0;

    Maze *mazPtr = (Maze *)malloc(sizeof (Maze));

    if(!mazPtr)
    {
        puts("The memory couldn't be initilised, Press ENTER to exit");
        getchar();
        exit(-1);
    }
    else
    {
        // allocating memory for the grid
    mazPtr->grid = (Cell **) malloc((sizeof (Cell)) * (mazPtr->rows));

    for(i = 0; i < mazPtr->rows; i++)
        mazPtr->grid[i] = (Cell *) malloc((sizeof (Cell)) * (mazPtr->cols));
    }

    return mazPtr;
}


void maz_delete(Maze *maz)
{
    int i = 0;

    if (maz != NULL)
        {
            for(i = 0; i < maz->rows; i++)
                free(maz->grid[i]);

            free(maz->grid);
        }
}


int main()
{
    Maze *ptr = maz_new();
    maz_delete(ptr);

    getchar();
    return 0;
}

提前致谢。

4

3 回答 3

1

除了 Marcelo 指出的问题之外,我还发现了这一点:

mazPtr->grid = (Cell **) malloc((sizeof (Cell)) * (mazPtr->rows));

您正在分配 10 个单元格,这将返回一个指向第一个单元格的指针,该指针的类型为Cell *. Cell结构是 abool和 a ,unsigned char根据编译器和目标体系结构,可能分配的空间不够大以容纳 a Cell *(可能是 64 位指针)。稍后初始化您的网格数组时,您可能最终会超出数组的末端。

sizeof (Cell *)所以,试着在你的网格中分配 10 个。当然,还要解决那里的初始化问题。

于 2010-05-08T11:27:11.047 回答
0

迷宫应该有多大?你永远不会初始化rowscols.

不过,您的大问题是您在初始化时使用了 sizeof(Cell) grid,但它应该是 sizeof(Cell*)。

在我的架构Cell上,只有两个字节,而是Cell *八个字节,这意味着您没有分配足够的空间。当你填写这个数组时,你正在写到末尾并写入其他分配的内存块,此时所有的赌注都被取消了。内存分配器在某些时候破坏了数组的内容,你只能试图释放垃圾。

于 2010-05-08T10:42:52.667 回答
0

在 maz_delete 中,您需要再次调用 free 以获取 maz 结构本身

无效maz_delete(迷宫*maz){int i = 0;

 if (maz != NULL)
 {
     for(i = 0; i < maz->rows; i++)
         free(maz->grid[i]);

     free(maz->grid);

     free(maz);
 }

}

于 2014-12-03T13:06:49.550 回答