C编程-Malloc/Free [英] C Programming- Malloc/Free
本文介绍了C编程-Malloc/Free的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个代码,当我运行它时,当我输入大于3的大小时,它会挂起.当它恰好是3时,它会平稳运行.我将问题缩小为malloc和free,但我不知道问题是什么.我是新来的,因此不胜感激.
So I have a code and when I run it, it hangs when I enter a size greater than 3. When it's exactly 3 it runs smoothly. I narrowed down the problem to malloc and free and I don't know what the problem is. I'm new at this so any help is appreciated.
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 failed\n");
for(i=0; i<size; i++)
{
if((board[i] = (char**)malloc(sizeof(char*)*size))==NULL)
printf("Memory Allocation failed\n");
for(j=0; j<size; j++)
{
if((board[i][j] = (char *)malloc(sizeof(char)*4))==NULL)
printf("Memory Allocation failed\n");
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
完全相反的顺序释放内存.
The problem is you access board
after you free
d 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);
这篇关于C编程-Malloc/Free的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文