c - 简单的动态内存分配错误

标签 c pointers memory-management malloc dynamic-memory-allocation

我确信您(专业人士)可以识别我的代码中的错误,我也希望对我的代码有任何其他评论。

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

#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/

相关文章:

c - 用DFS寻找无向图的连接点

c++ - 带有类指针的 if 语句导致段错误

文件中的字符重复 - 不区分大小写

matlab - 对从 Matlab 编译器运行时返回的 mxArray 对象调用 mxDestroyArray

javascript - Uint8Array 和 Uint8ClampedArray 之间的区别

c - 调用 mxCreateDoubleMatrix() 时什么会导致段错误?

c - 从文件中读取行,仅打印与用户选择的字母数量相同的行

c - p 在函数名 pwrite 和 pread 中代表什么?

c - 在函数之间传递 char 指针 - 两种方式是否相等? - C

java - 为什么JVM内存参数一般都是256的倍数?