2010-02-13 85 views
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?如果是这样的话,我该如何解脱?

+0

请注意,你的抽象可能是错的。它不是板子,它是一条条。考虑平方[N_BOARDSIZE,N_BOARDSIZE] – 2010-02-13 21:11:07

回答

7

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

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

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

+0

是的,从代码上主演完全是盲目的。谢谢 – Patrick 2010-02-13 21:06:39

2

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

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

它需要

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

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

你并不需要释放内阵列,因为它是一个固定大小的数组,当你分配一个board_type,这将是准备与整个数组。

修复的malloc,它会解决这个自由。

+0

是的,从代码上主演完全失明。谢谢 – Patrick 2010-02-13 21:07:22

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); 
0

另一个挑剔的问题,与你的记忆问题无关:如果你已经区分了三个可能的棋子,你可能不需要额外的标志来标记空闲的棋子十字架/圆/无......