我在源代码中使用(http://linux.die.net/man/3/hsearch)。我编写了一个非常基本的代码来测试哈希功能(不想通过编写自己的哈希实现来重新发明轮子)。我看到它在搜索例程中由于分段错误而崩溃。
知道为什么它崩溃了吗?
#include <stdio.h>
#include <search.h>
#include <stdlib.h>
char *data[] = {
"cpe1","cpe2","cpe3","cpe4","cpe5","cpe6","cpe7","cpe8","cpe9","cpe10","cpe11","cpe12","cpe13"};
int main()
{
ENTRY ep, ep1, *ep_ptr, ep2;
int loop;
char *ptr;
char input[100];
hcreate (30);
for (loop=0; loop<13;loop++)
{
ptr = malloc (100);
sprintf (ptr, "%d.%d.%d.%d%c", loop+1, loop*2, loop*3, loop, '\0');
ep.key = data[loop];
ep.data = (void *) ptr;
printf ("%s --> %s\n", ep.key, (char *) ep.data);
ep_ptr = hsearch(ep, ENTER);
}
ep2.data = (void *) "cpe1";
ep_ptr = hsearch(ep2, FIND);
printf("%9.9s -> %9.9s: %s\n", ep2.key,
ep_ptr ? ep_ptr->key : "NULL", ep_ptr ? (char *)(ep_ptr->data) : "NULL");
return 0;
}
输出:
(gdb) r
Starting program: /home/globus/code/cpe/a.out
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7ffff7ffa000
cpe1 --> 1.0.0.0
cpe2 --> 2.2.3.1
cpe3 --> 3.4.6.2
cpe4 --> 4.6.9.3
cpe5 --> 5.8.12.4
cpe6 --> 6.10.15.5
cpe7 --> 7.12.18.6
cpe8 --> 8.14.21.7
cpe9 --> 9.16.24.8
cpe10 --> 10.18.27.9
cpe11 --> 11.20.30.10
cpe12 --> 12.22.33.11
cpe13 --> 13.24.36.12
Program received signal SIGSEGV, Segmentation fault.
__strlen_sse2 () at ../sysdeps/x86_64/multiarch/../strlen.S:32
32 ../sysdeps/x86_64/multiarch/../strlen.S: No such file or directory.
(gdb) bt
#0 __strlen_sse2 () at ../sysdeps/x86_64/multiarch/../strlen.S:32
#1 0x00007ffff7b0ba71 in __GI_hsearch_r (item=..., action=FIND, retval=0x7fffffffdfd8,
htab=0x7ffff7dd67d0) at hsearch_r.c:149
#2 0x00007ffff7b0b92e in hsearch (item=..., action=<optimized out>)
at hsearch.c:34
#3 0x00000000004007a0 in main () at hash_test.c:32
(gdb)
最佳答案
搜索时,应将ep2.key
设置为搜索条目,而不是ep2.data
。因此,将您的代码更新为
//--v
ep2.key = (void *) "cpe1";
ep_ptr = hsearch(ep2, FIND);
由于尚未设置
ep2.key
,因此hsearch()
函数会尝试访问未初始化的指针,从而导致分段错误。关于c - hsearch中的分割错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25849575/