c - Where does hsearch store data? -
i'm playing around hash tables in c using hsearch. question in simplest form in memory data? thought hash table created hcreate pointed existing memory locations, info allocated means apart hcreate/hsearch (except of course of study hash table allocated hcreate).
to test wrote simple programme creates hash table. original info char array called "reply". pick array apart key/value pairs using strtok_r , create hash table hsearch. perform "look-up" hsearch, find key-value pair, clobber original memory, , look-up again. still find it. info beingness stored? didn't allocate special. here's test code can run see mean. should able compile gcc , run it.
class="snippet-code-html lang-html prettyprint-override">#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <search.h> #include <errno.h> #include <string.h> /** --------------------------------------------------------------------------- * store */ void store(char *key, char *value) { entry e, *ep; e.key = key; e.data = value; ep = hsearch(e, enter); if (ep == null) { perror("hsearch"); exit(1); } ep->data = (char *)value; } /** --------------------------------------------------------------------------- * fetch */ int fetch(char *key, char **value) { entry e, *ep; e.key=key; ep = hsearch(e, find); if (ep) { *value = (char *)ep->data; homecoming 1; } else homecoming 0; } /** --------------------------------------------------------------------------- * main */ void main( void ) { int i; char *saveptr, *token, *subtoken, *key, *value; // simulate reply string looks hardware... char reply[] = "backplane_type=1 backplane_rev=3 backplane_version=1.0.641 backplane_id=002428867071b05c power_id=000000ac19b4 mod_present=3f2"; hcreate(64); if ( (token = strtok_r(reply, " ", &saveptr)) != null ) { subtoken = strstr(token, "="); subtoken++; key = strsep(&token, "="); store(key, subtoken); } { if ((token = strtok_r(null, " ", &saveptr)) != null) { if ( (subtoken = strstr(token, "=")) == null ) break; subtoken++; if ( (key=strsep(&token, "=")) == null) break; } else break; store(key, subtoken); } while (1); // recall 1 of key-value pairs if (fetch((char*)"backplane_version", &value)) printf("ver = %s\n", value); // wipe out saveptr= subtoken= token= key= value=null; (i=0; i<strlen(reply); i++) reply[i]='\0'; // storage? if (fetch((char*)"backplane_version", &value)) printf("ver = %s\n", value); }
each info point different position of reply[]
array. can add together memset(reply, 0, sizeof(reply));
before sec fetch
, run. you'll nil sec fetch
.
c memory hash hashtable
No comments:
Post a Comment