猿问

同样的函数,同样的参数,不同的进程,结果不一样

#include
unsignedintgetHashNum(constchar*str,unsignedintlen,unsignedintmaxPrime)
{
registerunsignedintsum=0;
registerunsignedinth=0;
registerunsignedshort*p=(unsignedshort*)str;
registerunsignedshort*s=(unsignedshort*)str;
printf("str:%s,len:%d,h:%d,maxPrime:%d\n",p,len,h,maxPrime);
while(p-s{
registerunsignedshorta=*(p++)*(p-s);
printf("a:%d\n",a);
sum+=sum^a;
h+=a;
}
printf("sum:%d\n",sum);
return((sum<<16)|h)%maxPrime;
}
上面那段代码在主进程和子进程中都调用,传入的参数是一样的,但是返回值不一样,谁能看出来点端倪?
主进程输出:
str:key,len:3,h:0,maxPrime:60
a:0
a:121
a:49900
sum:49934
子进程输出:
str:key,len:3,h:0,maxPrime:60
a:0
a:121
a:29896
sum:29994
MM们
浏览 600回答 2
2回答

回首忆惘然

对str的操作越界了,unsignedshortp,p++实际往后对(char*)str移动了sizeof(unsignedshort)=4的距离,如果str长度为3,第一次循环就会跑出str的界,从而对p取值就说不定了。看出你的本意是按blocks对str求hash值(block大小是一个short),但是在实际指针操作过程有点问题。简单起见,你可以按单字节计算,将p,s指针类型改成unsignedchar×。如果想要实现按blocks计算,可以参考murmurhash方法。···unsignedintmurmur3_32(constchar*key,unsignedintlen,unsignedintseed){staticconstunsignedintc1=0xcc9e2d51;staticconstunsignedintc2=0x1b873593;staticconstunsignedintr1=15;staticconstunsignedintr2=13;staticconstunsignedintm=5;staticconstunsignedintn=0xe6546b64;unsignedinthash=seed;constintnblocks=len/4;constunsignedint*blocks=(constunsignedint*)key;inti;for(i=0;i>16);returnhash;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答