3

我无法真正理解为什么免费进程会返回错误。我在 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 吗?如果是这样,我该如何释放它?

4

4 回答 4

7

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

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

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

于 2010-02-13T20:55:16.250 回答
3

其他人已经指出了错误,但这里有一个宏可以帮助捕获这些错误:

#define NEW(type)   (type *)malloc(sizeof(type))

然后你会像这样使用它:

// Correct usage
board_type *board = NEW(board_type);

这样做的好处是,如果您像以前一样犯了错误,您应该得到一个编译器警告,指出由于宏内部的强制转换导致指针不匹配:

// Incorrect usage, a decent compiler will issue a warning
board_type *board = NEW(square_type);
于 2010-02-13T21:08:13.157 回答
2

首先,您在这里分配了错误的大小:

board_type *board = malloc(sizeof(square_type));

它需要是

board_type *board = malloc(sizeof(board_type));

您可能没有看到这个问题,但我怀疑您正在写入未分配的内存。(潜在的内存异常)。

你不需要释放内部数组,因为它是一个固定大小的数组,当你分配一个 board_type 时,它​​会准备好整个数组。

修复malloc,它将解决free。

于 2010-02-13T20:56:45.250 回答
0

另一个挑剔,与你的记忆问题无关:如果你已经区分了三个可能的部分 CROSS / CIRCLE / NONE,你可能不需要额外的标志来标记空闲方块......

于 2010-02-13T21:17:17.260 回答