![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Newbie
Join Date: Mar 2006
Posts: 1
Rep Power: 0
![]() |
Strange behavior: getting different results from the same input on a function. WTH?
I'm getting a strange behavior on this little script.
I'm trying to implement a hash table, so I have a hash function which should always return the same numeric result for a given string. Problem is, depending on the parent function which is calling hash(), it returns different results for the same string. If I call it twice inside the same function it works ok. Now the really strange thing (well, I don't know, maybe I'm doing something wrong - I'm new to C) is this behavior depends on the machine I'm running the script. At university machines, running Windows, I got the error. Then I tried at home on Windows and Linux, same thing. I then asked for a friend to try for me... it worked! http://francisco.datazero.net/myhash_fail.jpg http://francisco.datazero.net/myhash_ok.jpg You're encouraged to test it on your machine too to see if I'm going crazy. ![]() This is the code (quite simple script): #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASHELEMENTS 100
#define MAXLEN 100
struct htab {
struct htab *child;
struct htab *parent;
unsigned int key;
char value[MAXLEN];
};
struct htab *hashtab[HASHELEMENTS];
unsigned int hash (char *string) {
unsigned int hashval;
while (*string != '\0')
hashval += *string++;
return hashval % HASHELEMENTS;
}
// temporary debug functions
int testhash1(char *test1) {
unsigned int hashval;
return hash(test1);
}
int testhash2(char *test2) {
unsigned int hashval;
return hash(test2);
}
int main(){
char string[MAXLEN];
unsigned int hashval;
struct htab *curhash;
do {
printf("enter value to hash: ");
scanf("%s",&string);
printf("hash1: %d\n",testhash1(string));
printf("hash2: %d\n",testhash2(string));
} while (1); // use ctrl+c to exit
}Does anyone have any idea what's happening? |
|
|
|
|
|
#2 |
|
Expert Programmer
Join Date: Jun 2005
Posts: 893
Rep Power: 4
![]() |
unsigned int hash (char *string) {
unsigned int hashval = 0;
while (*string != '\0')
hashval += *string++;
return hashval % HASHELEMENTS;
}You have an uninitialised variable. The value that hashval starts with depends on what is currently in memory. Add in the code I put in red, above and you should be fine. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|