未初始化的价值valgrind

时间:2013-09-19 16:55:57

标签: c arrays valgrind

运行valgrind时,我收到Conditional jump or move depends on uninitialised value(s)消息。

我已经分配了一个指向struct数组的指针,我认为它与这个数组有关。

struct nlist **hashtab;

void init(void)
{
    hashtab = malloc(HASHSIZE * sizeof(*hashtab));
}

Valgrind消息:

valgrind --tool=memcheck --track-origins=yes bin/Zuul

==3131== Conditional jump or move depends on uninitialised value(s)
==3131==    at 0x400EF4: lookup (Dictionary.c:42)
==3131==    by 0x400DDE: install (Dictionary.c:18)
==3131==    by 0x4009A6: createItems (Game.c:42)
==3131==    by 0x400901: main (Game.c:19)
==3131==  Uninitialised value was created by a heap allocation
==3131==    at 0x4C2757B: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3131==    by 0x400DB9: init (Dictionary.c:9)
==3131==    by 0x4008FC: main (Game.c:16)

install()是从createItems()调用的第一个函数,它使用hashtab

struct nlist *install(char *name, listItem *_item)
{
    struct nlist *np;
    unsigned hashval;

    if ((np = lookup(name)) == NULL) {
        np = malloc(sizeof(*np));
        if (np == NULL || (np->name = strdupl(name)) == NULL)
            return NULL;

        hashval = hash(name);
        np->next = hashtab[hashval];
        np->_obj = _item;
        hashtab[hashval] = np;
    }
    else
        free((void *) np->_obj);

    return np;
}

查找功能:

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;

    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
            return np;

    return NULL;
}

hashtab之后的ddd中显示init()的值: Value of hashtab, displayed in ddd

1 个答案:

答案 0 :(得分:1)

Valgrind是对的。您永远不会在分配后初始化哈希表。您分配内存,但malloc()不保证已分配的内容(因此您的指针都是 indeterminate )。

执行此操作的一种可能方法是将init()更改为:

void init(void)
{
    hashtab = malloc(HASHSIZE * sizeof(*hashtab));
    for (unsigned int i=0;i<HASHSIZE; hashtab[i++] = NULL);
}

或另一个:

void init(void)
{
    hashtab = calloc(HASHSIZE, sizeof(*hashtab));
}

虽然纯粹主义者会说零填充不等于NULL填充。