2010-02-13 83 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

另一個挑剔的問題,與你的記憶問題無關:如果你已經區分了三個可能的棋子,你可能不需要額外的標誌來標記空閒的棋子十字架/圓/無......