2

When running valgrind, I'm getting a Conditional jump or move depends on uninitialised value(s) message.

I've allocated a pointer to struct array, and I think it has something to do with this array.

struct nlist **hashtab;

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

Valgrind message:

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() is the first function called from createItems(), which is using 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;
}

The lookup function:

/* 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;
}

Displaying the value of hashtab in ddd after init(): Value of hashtab, displayed in ddd

KLIM8D
  • 582
  • 1
  • 8
  • 25
  • Is Dictionary.c:42 the strcmp line in lookup()? And you should also test `s` and `np->name` for non-NULL values, since that's what `strcmp()` expects (valid strings) – grasbueschel Sep 19 '13 at 17:16
  • @grasbueschel Yes, line 42 in Dictionary.c is the call to `strcmp()`. – KLIM8D Sep 19 '13 at 17:34

1 Answers1

2

Valgrind is correct. You never initialize your hash table after allocation. You allocate the memory, but malloc() makes no guarantees of the allocated content (thus your pointers are all indeterminate).

One possible approach to doing this, change init() to this:

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

Or another:

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

though the purists will say zero-filled does not equate to NULL filled.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141