首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >内存释放失败

内存释放失败
EN

Stack Overflow用户
提问于 2010-02-14 04:51:46
回答 4查看 585关注 0票数 3

我不能真正理解为什么自由进程返回一个错误。我用C编写了这段代码:

代码语言:javascript
复制
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结构看起来像这样:

代码语言:javascript
复制
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?如果是这样的话,我如何释放它呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-02-14 04:55:16

我想你的malloc是错的。它应该是

代码语言:javascript
复制
board_type *board = malloc(sizeof(board_type)); /* instead of sizeof(square_type) ...*/

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

票数 7
EN

Stack Overflow用户

发布于 2010-02-14 05:08:13

其他人已经指出了错误,但这里有一个宏可以帮助捕获这些错误:

代码语言:javascript
复制
#define NEW(type)   (type *)malloc(sizeof(type))

然后,您可以这样使用它:

代码语言:javascript
复制
// Correct usage
board_type *board = NEW(board_type);

这样做的好处是,如果你像以前一样犯了一个错误,你应该得到一个编译器警告,指出由于宏内的强制转换导致指针不匹配:

代码语言:javascript
复制
// Incorrect usage, a decent compiler will issue a warning
board_type *board = NEW(square_type);
票数 3
EN

Stack Overflow用户

发布于 2010-02-14 04:56:45

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

代码语言:javascript
复制
board_type *board = malloc(sizeof(square_type));

它需要是

代码语言:javascript
复制
board_type *board = malloc(sizeof(board_type));

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

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

修复malloc,它将解决释放。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2259008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档