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を修正すると、無料で解決されます。

于 2010-02-13T20:56:45.250 に答える
0

もう1つの落とし穴は、メモリの問題とは関係ありません。CROSS/ CIRCLE / NONEの3つの可能な部分をすでに区別している場合は、空き正方形をマークするために追加のフラグはおそらく必要ありません。

于 2010-02-13T21:17:17.260 に答える