C Programming- Malloc/Free

不问归期 提交于 2019-12-06 11:13:47

The problem is you access board after you freed it. You should release memory in exactly the reverse order that you malloc it.

An alternative approach is that you can allocate all the memory you need in a whole, like

 char ***board = NULL;
 char  **rows  = NULL;
 char   *data  = NULL;

 if((board = (char***)malloc(sizeof(char**)*size))==NULL)
  printf("Memory Allocation failed\n");
 if((rows = (char**)malloc(sizeof(char*)*size*size))==NULL)
     printf("Memory Allocation failed\n");
 if((data = (char *)malloc(sizeof(char)*size*size*4))==NULL)  
     printf("Memory Allocation failed\n");

 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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!