我创建了存储数字数组的结构。该数组是动态分配的。尝试在函数中重新分配一些空间时,会发生此问题。错误是
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;
}
}
主要电话如下:
printf("Results:\n");
scale(num_b, 5, &pomocna);
print_big_number(pomocna);
free(pomocna.digits);
答案 0 :(得分:2)
数组从0
到n-1
。您正在写入array[n]
不存在
scaled->digits = malloc(scaled->num_of_digits * sizeof (unsigned int));
for (int i = scaled->num_of_digits; i >= 0; i--) { // AAA
int tmp = a.digits[i] * c + carry;
scaled->digits[i] = tmp % 10; // BBB
在AAA行中,将i
设置为数组的大小(为n
)
在BBB行中,您尝试更改scaled->digits[i]
(array[n]
)