我确信您(专业人士)可以识别我的代码中的错误,我也希望对我的代码有任何其他评论。
顺便说一句,代码在我运行后崩溃了。
#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;
}
提前致谢。
最佳答案
除了马塞洛指出的问题之外,我还发现了这一点:
mazPtr->grid = (Cell **) malloc((sizeof (Cell)) * (mazPtr->rows));
您要分配 10 个单元,这将返回一个指向第一个单元的指针,该单元的类型为 Cell *
。 Cell
结构是一个 bool
和一个 unsigned char
,根据编译器和目标架构,它可能没有分配足够大的空间来容纳Cell *
(可以是 64 位指针)。当稍后初始化网格数组时,您可能最终会写到数组的末尾。
因此,尝试在网格中分配 10 sizeof (Cell *)
。当然还要解决那里的初始化问题。
关于c - 简单的动态内存分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2793693/