在C中的结构内部释放结构数组

时间:2018-08-31 07:46:04

标签: c memory

我在C语言中有一个不了解的空闲内存错误。

我正在实现一个名为board的新结构,其中包含其他2种类型的数组:一个单元格数组和一个正方形数组。

typedef struct board2
{
    cell* cells;
    square* squares;
} board;


/*all three are initialized as such, whereas "size" is pre-calculated.*/
board gameBoard;
gameBoard = malloc(sizeof(board));
gameBoard->squares = calloc(size, sizeof(square));
gameBoard->cells = calloc(size*size, sizeof(cell));

使用free(gameBoard->cells)free(gameBoard.cells)将不起作用,它们分别提示不同的错误(第一个错误不编译,第二个错误在运行时失败)。我应该如何释放它?

2 个答案:

答案 0 :(得分:1)

从那时起,无需动态地将内存分配给结构对象 由于结构指针需要它,对于结构对象(如您在此处声明的那样),内存 静态分配,您无法在结构对象中捕获malloc返回的地址。

typedef struct board2
{
    cell* cells;
    square* squares;
} board;


/*all three are initialized as such, whereas "size" is pre-calculated.*/
board *gameBoard; // take the structure pointer .
gameBoard = malloc(sizeof(board));
gameBoard->squares = calloc(size, sizeof(square));
gameBoard->cells = calloc(size*size, sizeof(cell));

free(gameBoard->squares);
free(gameBoard->cells);
free(gameBoard);

答案 1 :(得分:0)

如果只有一个董事会,则无需使用gameBoard动态分配malloc()。只需使用您声明的变量即可。并且由于它不是指针,因此您应该使用.而不是->来访问成员。

board gameBoard;
gameBoard.squares = calloc(size, sizeof(square));
gameBoard.cells = calloc(size * size, sizeof(cell));

然后您以类似的方式释放它们:

free(gameBoard.squares);
free(gameBoard.cells);
相关问题