gpt4 book ai didi

c - 研究中的段错误

转载 作者:行者123 更新时间:2023-11-30 17:28:59 24 4
gpt4 key购买 nike

我在源代码中使用 ( 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.keyhsearch() 函数会尝试访问未初始化的指针,从而导致段错误。

关于c - 研究中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com