我正在用C做一个小游戏:这样的棋盘会显示出来:
|
|||
|||||
|||||||
而且你必须拿棍子并让AI输掉最后一根棒 . 想要让玩家能够选择我已经编写过以下功能的电路板尺寸:
char **disp_board(int size)
{
char **tab;
int i;
/*
* I malloc the board with the variable 'size' given by the user before the
* game starts
*/
if ((tab = malloc(sizeof(char *) * (size + 1))) == NULL)
return (NULL);
tab[size] = NULL;
i = 0;
while (i <= size)
{
if (i == 0)
{
if ((tab[i] = malloc(sizeof(char) + 1)) == NULL)
return (NULL);
tab[i] = my_strdup(my_strcat(tab[i], "|"));
i++;
}
if ((tab[i] = malloc(my_strlen(tab[i - 1]) + 3)) == NULL)
return (NULL);
tab[i] = my_strdup(my_strcat(tab[i - 1], "||"));
i++;
}
disp_board2(tab, size);
return (tab);
}
请注意 my_strdup
和 my_strcat
与 strdup
和 strcat
完全相同 .
但这是问题所在!游戏很常用,但有时候(特别是当我选择10和14尺寸时)我会收到以下消息:
“*** ./allum1中的错误:free():下一个大小无效(快):0x00000000022953f0 *** allum1:malloc.c:2365:sysmalloc:断言`(old_top ==(((mbinptr)((( char *)&((av) - > bins [((1) - 1)* 2])) - builtin_offsetof(struct malloc_chunk,fd))))&& old_size == 0)||((unsigned long)(old_size )> =(无符号长)((( builtin_offsetof(struct malloc_chunk,fd_nextsize))((2 *(sizeof(size_t))) - 1))~~((2 *(sizeof(size_t))) - 1) ))&&((old_top) - > size&0x1)&&((unsigned long)old_end&pagemask)== 0)'失败 . 中止“
所以我认为问题来自我的mallocs和frees,我再次检查,它们似乎都合乎逻辑!
提前感谢您的帮助,我真的希望我能解决这个问题 .
如果您对代码有任何疑问,请告诉我 .
2 回答
当你从
malloc
返回一个指针时,它没有指向任何特定的东西,当然也不是一个你可以连接到某个东西的有效字符串 . 将tab[i]
传递给my_strcat
(假设它是一个连接函数)没有任何意义,直到tab[i]
有一些理智的内容 .您在程序中进行了不必要的复杂化,在第(n-1)行的第n行构建依赖项,而您可以直接创建行 . 停止
strdup
ing,使用简单的malloc
memset
来创建并填充行: