我无法真正理解为什么免费进程会返回错误。我在 C 中得到了这个代码:

int LuffarschackStart(void)
{
/* to avoid the program from closing */
char readEnd;
int i = 0;

board_type *board = malloc(sizeof(square_type));
if (board == NULL)
{
    printf("Could not allocate the memory needed...");
    scanf("%c", &readEnd);
    return 0;
}

for(i = 0; i < 9; i = i + 1)
    board->square[i].piece_type = NO_PIECE;

board_play_game(board);

free(board);
printf("Press any key and enter to quit the program...");
scanf("%c", &readEnd);
return 0;
}

我正在分配的板结构如下所示:
typedef struct
{
    /* flag to indicate if a square is free or not */
    int free;
    /* the type of piece stored on the square if the
       square is not free, in this case the admissible
       values are CROSS_PIECE and CIRCLE_PIECE,
       otherwise the value NO_PIECE is used */
    int piece_type;
} square_type;

typedef struct
{
    square_type square[N_SQUARES];
    int computer_type;
    int player_type;
} board_type;

问题可能是我需要先释放板内的 square_type 吗?如果是这样,我该如何释放它?

最佳答案

我认为你的 malloc 是错误的。它应该是

board_type *board = malloc(sizeof(board_type)); /* instead of sizeof(square_type) ...*/

除此之外,我认为您的代码是正确的...

关于c - 释放内存失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2259008/

10-11 23:02
查看更多