首页 文章

'./a.out'中的错误:free():无效*** .`allum1'中的错误:free():下一个大小无效(快):0x00000000023e13f0 ***

提问于
浏览
0

我正在用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_strdupmy_strcatstrdupstrcat 完全相同 .

但这是问题所在!游戏很常用,但有时候(特别是当我选择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 回答

  • 3
    if ((tab[i] = malloc(sizeof(char) + 1)) == NULL)
            return (NULL);
          tab[i] = my_strdup(my_strcat(tab[i], "|"));
    

    当你从 malloc 返回一个指针时,它没有指向任何特定的东西,当然也不是一个你可以连接到某个东西的有效字符串 . 将 tab[i] 传递给 my_strcat (假设它是一个连接函数)没有任何意义,直到 tab[i] 有一些理智的内容 .

  • 0

    您在程序中进行了不必要的复杂化,在第(n-1)行的第n行构建依赖项,而您可以直接创建行 . 停止 strdup ing,使用简单的 malloc memset 来创建并填充行:

    for(i = 0; i < size; i++)
    {
        if ((tab[i] = malloc(2*i + 2)) == NULL) // create a string
          return (NULL);
        memset(tab[i], '|', 2*i + 1);           // fill it
        tab[i][2*i + 1] = 0;                    // add a terminator
    }
    

相关问题