我正在尝试使用 <search.h>
中的哈希表但我有一些困难。
在 man 中,他们说 hsearch 与 FIND 操作使用 strcmp 来确定您搜索的内容是否匹配。
正在做
add("foo");
find("foo");
此代码有效:
void add(char *word) {
ENTRY e, *ep;
e.key = word;
e.data = (int *) 1;
ep = hsearch(e, ENTER);
}
void find(char *word) {
ENTRY f, *fp;
f.key = word;
fp = hsearch(f, FIND);
if (fp == NULL) {
printf("This code does not work\n");
} else {
printf("This code works\n");
}
}
这个没有
void add(char *word) {
ENTRY e, *ep;
char newWord[100];
strcpy(newWord, word);
e.key = newWord;
e.data = (int *) 1;
ep = hsearch(e, ENTER);
if (strcmp(word, newWord) == 0) {
printf("According to strcmp, those words are equals\n");
}
}
我必须执行 strcpy 行,因为我需要将单词转换为小写,并且我必须能够执行 add("sOmeTHing")。使用 malloc 我设法做我想做的一切,但我担心我无法释放任何东西......
你能帮我一下吗? :)
最佳答案
您正在存储一个指向“newWord”空间的指针,超出其生命周期。换句话说,“newWord”是函数“add”的本地函数,这意味着当函数返回时它就会消失。发生这种情况时,您存储的地址 - e.key = newWord
就会变为悬空。
Using malloc I managed to do everything I wanna do, but I'm affraid I can't free anything
使用 malloc
是处理此问题的一种比较明智的方法:您需要一个比函数生命周期更长的对象。
真正的解决方案是使用允许您传递自己的比较函数的 API。与这个问题相比,hsearch
和 friend 是由 POSIX 指定的这一事实是一个小小的好处。
Linux 手册确实提供了这些释放内存的“解决方案”:
If these buffers need to be freed (perhaps because the program is repeatedly creating and destroying hash tables, rather than creating a single table whose lifetime matches that of the program), then the program must maintain bookkeeping data structures that allow it to free them.
关于c - 如何在 hsearch 之前操作字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663431/