【发布时间】:2014-11-06 21:13:06
【问题描述】:
我正在使用 hsearch 在 C 中处理哈希表。最简单的问题是内存中的数据在哪里?我认为 hcreate 创建的哈希表只是指向现有的内存位置,所以数据是通过 hcreate/hsearch 之外的方式分配的(当然除了 hcreate 分配的哈希表本身)。
为了测试这一点,我编写了一个创建哈希表的简单程序。原始数据是一个名为“reply”的字符数组。我使用 strtok_r 将数组分成键/值对,然后使用 hsearch 创建哈希表。我使用 hsearch 执行“查找”,找到我的键值对,然后我破坏原始内存,并再次进行查找。我还是找到了。那么数据存储在哪里呢?我没有分配任何特别的东西。这是一些测试代码,您可以运行以了解我的意思。你应该可以用 gcc 编译并运行它。
#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;
return 1;
}
else
return 0;
}
/** ---------------------------------------------------------------------------
* main
*/
void main( void ) {
int i;
char *saveptr, *token, *subtoken, *key, *value;
// this is to simulate what a reply string looks like from my 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);
}
do {
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 one of the key-value pairs
if (fetch((char*)"BACKPLANE_VERSION", &value)) printf("VER = %s\n", value);
// wipe everything out
saveptr= subtoken= token= key= value=NULL;
for (i=0; i<strlen(reply); i++) reply[i]='\0';
// where is the storage?
if (fetch((char*)"BACKPLANE_VERSION", &value)) printf("VER = %s\n", value);
}
【问题讨论】: