2

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

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

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()hashtab 的值,显示在 ddd

4

1 回答 1

2

瓦尔格林是正确的。您永远不会在分配后初始化哈希表。您分配内存,但malloc()不保证分配的内容(因此您的指针都是不确定的)。

执行此操作的一种可能方法,更改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 填充。

于 2013-09-19T17:14:56.467 回答