使用realloc()crahes程序

Jor*_*ori 1 c realloc

我使用时遇到了一些问题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;
}
Run Code Online (Sandbox Code Playgroud)

这输出:

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

为什么会崩溃?

编辑: 我试图chaning (i + 1)来(i + 2),然后程序的工作,但我不明白为什么.我只要求将内存空间扩展一个 unsigned long long.

Nbr*_*r44 12

循环第一次运行,i等于0.你realloc a保持i + 1元素,这是...... 1!第二次循环运行时,您尝试写入a[i]with i == 1,这是数组的第二个元素.但由于您的数组只能保存1元素,因此可能导致崩溃.