insert - Hashtable in C: Does testing functions using manual arguments differ from user inputted arguments -
my problem rather odd one. when tested functions manually worked, returned random result when let user input arguments.
to better explain myself, writing hash table using binary trees instead of linked lists (which part of assignment). is, in event of hash collision data chains binary search tree.
i have finished of functions, in terms of testing, manually inputted arguments. set arguments inside tester rather having user type in when program runs. works fine , functions returns suppose return. however, when tried user input, insert , delete behaving strangely. instance, delete, supposed return value deleted. however, gave me value value of node in bst.
manual input code snippet: inserted key = "111" , value = "d" manually
char ** preval = calloc(1, sizeof(char *)); insertentry(*hthandle, "111", (void *) "d", (void **) preval); printf("existing value %s removed\n", *preval); free(preval);
result: returned correct output, expected instructions given. there more key-value pairs entered before (this small chunk of code, assume hthandle hash table pointer).
user input tester wrote (another snippet of code):
if (strcmp(str, "insert") == 0) { char key[50]; printf("key: "); scanf("%s", key); char value[50]; printf("item: "); scanf("%s", value); char ** preval = calloc(1, sizeof(char *)); int success = insertentry(*hthandle, key, (void *) value, (void **) preval); ... if (success == 2) printf("node exists - inserted after removing existing data: %s\n", *preval); ... free(preval); } result: here preval points data of last key-value pair in bst or entered one, or other random one.
any advice helpful. thanks.
however, when tried user input, insert , delete behaving strangely. instance, delete, supposed return value deleted. however, gave me value value of node in bst.
it looks storing pointers strings, rather strings. perhaps reusing same buffer user input? need see how store , pass user input, , maybe code insertentry()
answer question.
but there's interesting issue here:
char ** preval = calloc(1, sizeof(char *)); int success = insertentry(*hthandle, key, (void *) value, (void **) preval); ... free (preval);
there's simpler way allocate storage pointer, , return value through function argument:
char *preval; int success = insertentry(*hthandle, key, (void *) value, (void **)&preval);
however, conversion char **
void **
bit suspicious. works because void *
, char *
guranteed have same representation , alignment. there no such guarantee other pointer types. if wanted store int
s, example, you'd have write:
int *preval; void *vp; int success = insertentry(*hthandle, key, (void *) value, &vp); preval = vp;
an int *
can converted void *
, back, same not hold int **
, void **
, need variable store return value. has nice effect of eliminating need (void **)
cast. personally, remove all of (void *)
casts above. unlikely needed.
Comments
Post a Comment