我写了一段代码来实现哈希函数。将第 9 个元素“a12a”添加到列表时出现问题,gdb 报告如下,似乎问题是在 malloc 应用内存期间发生的。但是在添加第9个元素之前,我曾经在添加第6个元素“ad”时通过malloc成功申请了一次内存,为什么第二次申请内存失败?
Breakpoint 1, insert (p=0x3d2d10, value=0x4030e8 "a12a") at hashop.c:39
39 id = hash(value);
(gdb) n
40 *current = p + id;
(gdb)
41 if((*current)->value == NULL) {
(gdb)
44 if((lookup(p+id, value)) == NULL) {
(gdb)
45 new = (nList *)malloc(sizeof(nList));
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0x7c938996 in ntdll!RtlDuplicateUnicodeString ()
from C:\WINDOWS\system32\ntdll.dll
(gdb)
我的代码是:
void insert(nList *p, char *value)
{
nList *new, **current;
int id;
id = hash(value);
*current = p + id;
if((*current)->value == NULL) {
(*current)->value = value;
} else {
if((lookup(p+id, value)) == NULL) {
new = (nList *)malloc(sizeof(nList));
new->value = value;
new->next = NULL;
while((*current)->next != NULL) {
(*current) =(*current)->next;
}
(*current)->next = new;
}
}
}
static char *str2[] = {"ac", "ba", "abv", "bc", "bx", "ad", "xx", "aaa", "a12a", "b123"};
每个元素的hash id如下:
ac, HashId=6
ba, HashId=5
abv, HashId=3
bc, HashId=7
bx, HashId=8
ad, HashId=7
xx, HashId=0
aaa, HashId=1
a12a, HashId=3
b123, HashId=8
从上面的列表中,可以确定“bc”和“ad”具有相同的哈希 id,所以在我的 insert() 函数中,我将应用一块内存来存储“ad”。“abv”和“a12a”也是一样,我也申请了一块内存,但这次失败了。为什么?任何人都可以弄清楚吗?赞赏!