使用realloc()崩溃程序

时间:2013-07-29 09:16:32

标签: 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;
}

输出:

  

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

为什么这会崩溃?

修改 我尝试将(i + 1)转换为(i + 2)然后该程序有效,但我不明白为什么。我只要求一个 unsigned long long扩展内存空间。

2 个答案:

答案 0 :(得分:12)

第一次循环运行时,i等于0。您重新分配a以保留i + 1个元素,即1! 第二次循环运行时,您尝试使用a[i]写入i == 1,这是数组的第二个元素。但由于您的数组只能保存1元素,因此可能导致崩溃。

答案 1 :(得分:0)

您正在分配位置i,但访问位置i+1

在退出

之前不要忘记释放已分配的内存
free(a);

这样修改就可以使这段代码正常工作

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;
    }
相关问题