0
votes

I have been trying to fix the memory leaks in my program. This is the piece of code that causes the error:

unsigned long me_hash(MEntry *me, unsigned long size) {

    unsigned long hash;
    unsigned long hash_init;
    int i;

    hash = 0;
    hash_init = 0;

    for (i = 0; me -> surname[hash_init] != '\0'; i++) {
        hash_init += (int) me -> surname[i];
    }

    hash += 5381*hash_init;

    for (i = 0, hash_init = 0; me -> postcode[hash_init] != '\0'; i++) {
        hash_init += (int) me -> postcode[i];
    }

    hash_init = hash_init + me -> house_number;

    hash += 5381*hash_init;

    hash = hash%size;

    return hash;
}

This is the result printed on my terminal when I run Valgrind:

==7853== Conditional jump or move depends on uninitialised value(s)
==7853==    at 0x40116D: me_hash (in /home/iva/University/AdvProg/Assessed/a.out)
==7853==    by 0x400D7A: ml_lookup (in /home/iva/University/AdvProg/Assessed/a.out)
==7853==    by 0x4013CD: main (in /home/iva/University/AdvProg/Assessed/a.out)

Any help with this will be really really appreciated.

1
Did you compile with -g ? - Jonathon Reinhart
First I compiled it with gcc -W program.c Then I used valgrind --tool=memcheck --track-origins=yes --leak-check=full --read-var-info=yes -v ./a.out - Iva
Add -g (and -Wall -Wextra -std=c99 while you're at it) to get line numbers in valgrind's output. - Mat
Okay well try adding -g to your GCC command line. That will include debug info that will allow valgrind to give you more detail about errors. - Jonathon Reinhart
I did it, thanks for the advise, now it shows the line numbers: - Iva

1 Answers

1
votes
for (i = 0; me -> surname[hash_init] != '\0'; i++) {
    hash_init += (int) me -> surname[i];
}

You have a bad loop condition above. It should probably be:

for (i = 0; me -> surname[i]; i++) {
    hash_init += (int) me -> surname[i];
}

Same issue for the second loop.