[英]void pointer cast to a char pointer crashes when dereferencing
I'm trying to implement DJB algorithim in C to build a dictionary like structure.我正在尝试在 C 中实现 DJB 算法来构建一个类似结构的字典。
My implementation works well if the key passed is a char pointer however if i pass for example a integer it crashes, I'm not sure why and how could i accomplish this.如果传递的键是一个字符指针,我的实现运行良好,但是如果我传递例如一个整数它会崩溃,我不知道为什么以及如何实现这一点。 Basically I'd need to hash both a string and a integer.
基本上我需要散列一个字符串和一个整数。
static unsigned int DJBHash(void* key, unsigned int len) {
unsigned int hash = 5381;
unsigned int i = 0;
char* ptr = (char *)key;
for (i = 0; i < len; i++)
{
hash += hash << 5;
hash += *ptr; /* crashes if key is not originally a char* */
ptr++;
}
return hash;
}
this get simply called to get an hash value: DJBHash((void*)420, sizeof(420));
简单地调用它以获取哈希值:
DJBHash((void*)420, sizeof(420));
crashses while DJB((void*)"foo", sizeof("foo"));
DJB((void*)"foo", sizeof("foo"));
崩溃DJB((void*)"foo", sizeof("foo"));
works perfectly fine.工作得很好。
DJBHash(420, sizeof(420));
crashses while DJB("foo", sizeof("foo"));
DJB("foo", sizeof("foo"));
崩溃DJB("foo", sizeof("foo"));
works perfectly fine.工作得很好。
That's because using 420
isn't a valid memory address in your program.那是因为在程序中使用
420
不是有效的内存地址。 So when your function tries to use that memory address it crashes.因此,当您的函数尝试使用该内存地址时,它会崩溃。 Normally you wouldn't even try to force a specific memory address in this fashion.
通常,您甚至不会尝试以这种方式强制使用特定的内存地址。 It only works in very specific cases like when its a known address in kernel space or something like that.
它仅适用于非常特定的情况,例如内核空间中的已知地址或类似的情况。
If you want to hash an integer instead of specific memory location it would be:如果你想散列一个整数而不是特定的内存位置,它将是:
int j = 420;
DJBHash(&j, sizeof(j));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.