1

我在使用时遇到了一些问题realloc(),所以我制作了一个示例程序来说明使用尽可能少的代码的问题。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    unsigned int i;
    unsigned long long *a;
    srand(time(NULL));
    a = malloc(sizeof(unsigned long long));
    for (i = 0; i < 20; ++i)
    {
        a[i] = rand() % 32;
        printf("%llu\n", a[i]);
        a = realloc(a, (i + 1) * sizeof(unsigned long long));
    }
    return 0;
}

这输出:

* 检测到 glibc演示:realloc():下一个大小无效:0x0000000000dc3010 * *

为什么会崩溃?

编辑: 我尝试(i + 1)更改为(i + 2)然后程序运行,但我不明白为什么。我只要求将内存空间扩展 unsigned long long

4

2 回答 2

12

您的循环第一次运行时,i等于0. 你a重新分配来保存i + 1元素,这是...... 1!循环第二次运行时,您尝试写入a[i]with i == 1,这是数组的第二个元素。但是由于您的数组只能容纳1元素,这可能会导致崩溃。

于 2013-07-29T09:21:56.640 回答
0

You are allocating location i but accessing location i+1

And do not forget to free the allocated memory before exiting

free(a);

So do this modification to make this code work

a = realloc(a, (i + 2) * sizeof(unsigned long long)); // ERROR HERE

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

    int main(void)
    {
        unsigned int i;
        unsigned long long *a;
        srand(time(NULL));
        a = malloc(sizeof(unsigned long long));
        for (i = 0; i < 20; ++i)
        {
            a[i] = rand() % 32;
            printf("%llu\n", a[i]);
            a = realloc(a, (i + 1) * sizeof(unsigned long long)); // ERROR HERE
        }
        return 0;
    }
于 2013-07-29T09:21:42.633 回答