【问题标题】:Recursive realloc() throw "invalid next size" after the 7th cicle递归 realloc() 在第 7 圈后抛出“无效的下一个大小”
【发布时间】:2019-01-16 14:28:33
【问题描述】:

所以,我有一个指针需要增加它的“长度”,直到用户插入一个负数或“e”。它以“1”的长度开始,通过malloc() 然后我在do{...} while(...) 循环中使用realloc() 函数来增加它的长度。代码如下:

int *array = malloc (sizeof(int) * 1);
bool exit = false;
int lastIndex = 0, value;

do {
    printf ("Insert a positive number. Insert a negative number or \"e\" to exit:  ");

    int scanf_result = scanf("%i", &value);
    if (scanf_result) {
      if (value >= 0) {
        array[lastIndex] = value;
        lastIndex++;
        array = (int*) realloc (array, lastIndex * sizeof(int));
      } else {
        exit = true;
      }
    } else {
      exit = true;
    }
} while (!exit);

我不明白为什么在第 7 个 cicle 之后它退出并出现错误 realloc(): invalid next size

有什么想法吗?感谢您的建议。

【问题讨论】:

  • 关于:int scanf_result = scanf("%i", &value); if (scanf_result) 'this' 调用到scanf() 的返回值可以返回 0、1 或 EOF。所以if() 语句无效。应该是:if( scanf_result == 1 ) 任何其他返回值都表示发生了错误。
  • 关于:array = (int*) realloc (array, lastIndex * sizeof(int)); 1) 在 C 中,来自 malloccallocrealloc 的返回值的类型为 void*,可以分配给任何指针,铸造只会使代码,使其更难理解、调试等。 2) 在调用realloc() 时,切勿将返回值直接赋给目标指针。而是分配给“临时”变量,然后检查 (!=NULL),如果成功,则从临时指针分配目标指针。否则当realloc()失败时原始指针丢失,导致内存泄漏
  • 关于:printf ("Insert a positive number. Insert a negative number or \"e\" to exit: "); 建议输入“e”。 'e' 永远不会通过语句输入:if (scanf_result) {,因为格式字符串:“%i”。但是,程序可能会正确处理。但是,如果用户根据操作系统输入 (或 ),这将被视为有效输入

标签: c pointers int malloc realloc


【解决方案1】:

你没有重新分配足够的内存:

array = (int*) realloc (array, lastIndex * sizeof(int));

在循环的第一次迭代中,lastIndex 从 0 递增到 1,然后运行上面的 realloc 调用。由于lastIndex 为 1,因此您仍然只有足够的空间容纳 1 个元素。结果,您在下一次迭代中写入超过分配内存的末尾。

这会调用undefined behavior,在您的情况下,这表现为前 6 次迭代似乎正常工作,而在第 7 次迭代失败。它可能在第一次或第二次迭代时很容易崩溃。

在您分配的大小上加一:

array = realloc(array, (lastIndex + 1) * sizeof(int));

另外,don't cast the return value of malloc/realloc

【讨论】:

    【解决方案2】:

    修复你的realloc

    array = (int*) realloc (array, (lastIndex + 1) * sizeof(int))
    

    您分配的项目比您需要的少。

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 1970-01-01
      • 2014-10-13
      • 2015-01-22
      • 1970-01-01
      • 2016-01-02
      • 2019-08-29
      相关资源
      最近更新 更多