第 7 圈后递归 realloc() throw "invalid next size"
Recursive realloc() throw "invalid next size" after the 7th cicle
所以,我有一个指针需要增加它的 "length",直到用户插入一个负数或 "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 个循环后它退出并出现错误 realloc(): invalid next size
。
有什么想法吗?感谢您的帮助。
修正你的 realloc
:
array = (int*) realloc (array, (lastIndex + 1) * sizeof(int))
您分配的项目比您需要的少。
您没有重新分配足够的内存:
array = (int*) realloc (array, lastIndex * sizeof(int));
在循环的第一次迭代中,lastIndex
从 0 递增到 1,然后您 运行 上面的 realloc
调用。由于 lastIndex
为 1,因此您仍然只有足够的 space 用于 1 个元素。结果,您在下一次迭代中写入了已分配内存的末尾。
这会调用 undefined behavior,在您的情况下,它表现为前 6 次迭代似乎正常工作,但在第 7 次迭代时失败。它可能在第一次或第二次迭代时很容易崩溃。
将您分配的大小加一:
array = realloc(array, (lastIndex + 1) * sizeof(int));
此外,don't cast the return value of malloc
/realloc
。
所以,我有一个指针需要增加它的 "length",直到用户插入一个负数或 "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 个循环后它退出并出现错误 realloc(): invalid next size
。
有什么想法吗?感谢您的帮助。
修正你的 realloc
:
array = (int*) realloc (array, (lastIndex + 1) * sizeof(int))
您分配的项目比您需要的少。
您没有重新分配足够的内存:
array = (int*) realloc (array, lastIndex * sizeof(int));
在循环的第一次迭代中,lastIndex
从 0 递增到 1,然后您 运行 上面的 realloc
调用。由于 lastIndex
为 1,因此您仍然只有足够的 space 用于 1 个元素。结果,您在下一次迭代中写入了已分配内存的末尾。
这会调用 undefined behavior,在您的情况下,它表现为前 6 次迭代似乎正常工作,但在第 7 次迭代时失败。它可能在第一次或第二次迭代时很容易崩溃。
将您分配的大小加一:
array = realloc(array, (lastIndex + 1) * sizeof(int));
此外,don't cast the return value of malloc
/realloc
。