我不能真正理解为什么自由进程返回一个错误。我用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;
}我分配的board结构看起来像这样:
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?如果是这样的话,我如何释放它呢?
发布于 2010-02-14 04:55:16
我想你的malloc是错的。它应该是
board_type *board = malloc(sizeof(board_type)); /* instead of sizeof(square_type) ...*/除此之外,我认为你的代码是正确的。
发布于 2010-02-14 05:08:13
其他人已经指出了错误,但这里有一个宏可以帮助捕获这些错误:
#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-14 04:56:45
首先,您在这里分配了错误的大小:
board_type *board = malloc(sizeof(square_type));它需要是
board_type *board = malloc(sizeof(board_type));您可能没有看到这个问题,但我怀疑您正在写入未分配的内存。(潜在的内存异常)。
您不需要释放内部数组,因为它是固定大小的数组,并且当您分配board_type时,它将与整个数组一起准备就绪。
修复malloc,它将解决释放。
https://stackoverflow.com/questions/2259008
复制相似问题