realloc():两次计算后的下一个大小无效

时间:2019-04-08 16:00:10

标签: c function malloc structure realloc

我创建了存储数字数组的结构。该数组是动态分配的。尝试在函数中重新分配一些空间时,会发生此问题。错误是

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);

1 个答案:

答案 0 :(得分:2)

数组从0n-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]