C Programming- Malloc/Free



所以我有一个代码,当我运行它时,当我输入大于 3 的大小时它会挂起。当它正好是 3 时,它运行平稳。我将问题缩小到malloc和free,我不知道问题是什么。我是新手,所以任何帮助都值得赞赏。

do  //repeatedly ask the user to put a number between 3-9
{ 
 printf("Enter the size of the game board between 3-9: ");
 scanf("%d", &size);
}while(size<3 || size>9);
if((board = (char***)malloc(sizeof(char**)*size))==NULL)
  printf("Memory Allocation failedn");
  for(i=0; i<size; i++)
  {
    if((board[i] = (char**)malloc(sizeof(char*)*size))==NULL)
     printf("Memory Allocation failedn");
     for(j=0; j<size; j++)
     {
       if((board[i][j] = (char *)malloc(sizeof(char)*4))==NULL)  
         printf("Memory Allocation failedn");
         strcpy(board[i][j], "Go");
     }   
 } 
/*************Some random code ***********/ 
free(board);
for(i=0;i<size;i++)
{
 free(board[i]);
 for(j=0;j<size;j++)
   free(board[i][j]);
}

问题是你在free d 后访问board。您应该以与malloc内存完全相反的顺序释放内存。

另一种方法是,您可以将所需的所有内存分配为一个整体,例如

 char ***board = NULL;
 char  **rows  = NULL;
 char   *data  = NULL;
 if((board = (char***)malloc(sizeof(char**)*size))==NULL)
  printf("Memory Allocation failedn");
 if((rows = (char**)malloc(sizeof(char*)*size*size))==NULL)
     printf("Memory Allocation failedn");
 if((data = (char *)malloc(sizeof(char)*size*size*4))==NULL)  
     printf("Memory Allocation failedn");
 for (i = 0; i < size; i++) {
     int board_offset = i * size;
     board[i] = rows[board_offset];
     for (j = 0; j < size; j++) {
         int row_offset = board_offset + j;
         rows[row_offset] = data[row_offset * 4];
         stcpy(data[row_offset * 4], "GO");
     }
 }
 free(board);
 free(rows);
 free(data);

相关内容

  • 没有找到相关文章

最新更新