【问题标题】:realloc(): invalid next size after two computationsrealloc():两次计算后下一个大小无效
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 这解决了问题,我没有注意到数组索引的错误。谢谢。
猜你喜欢
  • 2020-12-27
  • 1970-01-01
  • 2014-10-13
  • 2015-01-22
  • 1970-01-01
  • 2020-07-24
  • 2017-06-18
相关资源
最近更新 更多