c语言 - 递归 realloc() 在第 7 个 cicle 之后抛出"invalid next size"



所以,我有一个指针需要增加它的"长度",直到用户插入负数或"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.

知道吗?感谢您的帮助。

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

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

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

这将调用未定义的行为,在您的情况下,该行为表现为在前 6 次迭代中似乎正常工作,并在第 7 次迭代中失败。 它可能在第一次或第二次迭代中很容易崩溃。

将一个添加到要分配的大小中:

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

另外,不要强制转换 malloc/realloc 的返回值。

修复您的realloc

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

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

相关内容

最新更新