生成1000万UUID时uuid_generate_random崩溃

时间:2013-10-22 08:46:31

标签: c hash uuid

我试图测试xxhash功能。所以我写了一个简单的程序来生成UUID并将其传递给XXH32函数。这是我的计划:

#define UUID_LEN 36

int main(int argc, char **argv)
{
    uuid_t id;
    char cid[UUID_LEN + 1];

    int hash_count = atoi(argv[1]);
    unsigned int hash[hash_count];

    for(int i = 0;i < hash_count;i++) {
        uuid_generate_random(id);
        uuid_unparse(id, cid);

        hash[i] = XXH32(cid, UUID_LEN, time(NULL));

        uuid_clear(id);
    }

    return 0;
}

我将哈希生成次数作为参数(./main 100)传递。程序运行正常,但当我通过100万时它显示:Segmentation fault (core dumped)。我安装了所有的debuginfo包。当我用gdb打开核心文件时,它会显示:

Reading symbols from /home/m.azimi/projects/testtommy/main...done.
[New LWP 8117]
Core was generated by `./main 10000000'.
Program terminated with signal 11, Segmentation fault.
#0  0x00000000004008e0 in main (argc=2, argv=0x7fffe19da598) at main.c:19
19          uuid_generate_random(id);

我用uuid_generate试了一下但没有用。我使用带有完全更新包的fedora 19。您可以从here下载核心文件。

[UPDATE]

基于@Tarik评论,我改为hash[i % 10000] = XXH32(cid, UUID_LEN, time(NULL));,现在工作正常。另外我只保存生成的整数哈希值。因此内存使用量为10,000,000 * 4字节= 40MB。接下来我将程序更改为:

int main(int argc, char **argv)
{
    /* allocate 10 million 4byte chunk = 40MB */
    unsigned int hash[10000000];

    return 0;
}

这也是核心崩溃:

[New LWP 13593]
Core was generated by `./main'.
Program terminated with signal 11, Segmentation fault.
#0  0x000000000040068b in main (argc=<error reading variable: Cannot access memory at address 0x7fff244a388c>, 
    argv=<error reading variable: Cannot access memory at address 0x7fff244a3880>) at main.c:9
9   {

可以从here下载新的核心文件。为什么会这样?是否有任何操作系统级别限制?这是从堆栈而不是堆分配内存吗?因为unsigned int *hash = (unsigned int *) malloc(sizeof(unsigned int) * 10000000);没有问题。

1 个答案:

答案 0 :(得分:1)

我想我已经钉了它。使用malloc()从堆而不是堆栈动态分配内存。我记得过去面对同样的问题。