gpt4 book ai didi

c - Redis添加 `dict`时地址边界错误如何解决?

转载 作者:行者123 更新时间:2023-11-30 14:34:44 25 4
gpt4 key购买 nike

我想基于 dict 进行一些基本的 put/get 测试。但是在执行dictAdd时,抛出了错误。

代码

// dict_test.c
#include <stdio.h>
#include "dict.h"

int main(int argc, char *argv[]) {
// create
dictType hashDictType;
dict *d = dictCreate(&hashDictType, NULL);
printf("Created: %s\n", d == NULL ? "Failed" : "OK");
// put
char key[] = "hello";
char value[] = "world";
dictAdd(d, key, value);
return 0;
}

错误消息

“./dict_test”由信号 SIGSEGV(地址边界错误)终止

GCC版本

Apple LLVM 版本 10.0.1 (clang-1001.0.46.4)

编译命令

gcc dict_test.c dict.c zmalloc.c siphash.c  -o dict_test

我发现执行 dictIsRehashing(d) 时抛出错误,它是一个宏(#define dictIsRehashing(d) ((d)->rehashidx != -1)).

所以我尝试直接打印 d->rehashidx 。但我仍然遇到同样的错误。

printf("%ld \n", d->rehashidx);
printf("%s", ((d)->rehashidx) == -1L ? "False" : "True");

输出

Created: OK
-1
fish: './dict_test' terminated by signal SIGSEGV (Address boundary error)

也许这是一个基本的c问题。任何提示将不胜感激。

重现步骤

  1. 我下载了Redis的源代码:)。
  2. 将演示代码粘贴到src目录下。

最佳答案

OP 的解决方案。

问题是当使用 dict 时,需要您自己初始化一个哈希函数,我认为它有一个默认函数。通过定义一个哈希函数,解决了崩溃问题。

#include <stdio.h>
#include <strings.h>
#include "dict.h"

// a hash function defined
uint64_t dictSdsCaseHash(const void *key) {
// refer to "siphash.c"
return dictGenCaseHashFunction((unsigned char*)key, (int) strlen((char*)key));
}

int main(int argc, char *argv[]) {
// create
dictType hashDictType;
hashDictType.hashFunction = dictSdsCaseHash;
dict *d = dictCreate(&hashDictType, NULL);
printf("Created: %s\n", d == NULL ? "Failed" : "OK");
// put
char key[] = "hello";
char value[] = "world";
dictAdd(d, key, value);
// get
dictEntry *entry = dictFind(d, key);
printf("Value: %s\n", entry->v);
return 0;
}

输出

Created: OK
hello
Value: world

关于c - Redis添加 `dict`时地址边界错误如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58851956/

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