【发布时间】:2019-08-29 20:05:38
【问题描述】:
我创建了存储数字数组的结构。数组是动态分配的。尝试重新分配函数中的一些空间时会出现问题。错误是
realloc(): invalid next size
Aborted (core dumped)
结构如下
typedef struct big_number {
unsigned int *digits;
int num_of_digits;
}BigNumber;
函数如下所示(将数字与 BigNumber 相乘):
void scale(BigNumber a, int c, BigNumber* scaled)
{
scaled->num_of_digits = a.num_of_digits;
scaled->digits = NULL;
scaled->digits = malloc(scaled->num_of_digits * sizeof (unsigned int));
if (scaled->digits == NULL) {
error();
}
int carry = 0;
for (int i = scaled->num_of_digits; i >= 0; i--) {
int tmp = a.digits[i] * c + carry;
scaled->digits[i] = tmp % 10;
carry = tmp / 10;
}
if (carry != 0) {
//While trying realloc in this line problem occurs
scaled->num_of_digits += 1;
scaled->digits = realloc(scaled->digits, scaled->num_of_digits * sizeof (unsigned int));
scaled->digits[0] = carry;
}
}
main 中的调用如下所示:
printf("Results:\n");
scale(num_b, 5, &pomocna);
print_big_number(pomocna);
free(pomocna.digits);
【问题讨论】:
-
realloc应始终分配给一个中间指针变量,而不是为错误情况处理重新分配的同一个变量(您没有这样做)。
标签: c function malloc structure realloc