没有释放记忆

时间:2010-02-13 20:51:46

标签: c memory free malloc

我无法真正理解为什么自由进程会返回错误。我在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 个答案:

答案 0 :(得分:7)

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

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

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

答案 1 :(得分: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);

答案 2 :(得分:2)

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

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

需要

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

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

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

修复malloc,它将解决免费问题。

答案 3 :(得分:0)

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