Reputation: 111
I have the following simple hashing function and I was just playing around the code but found something weird(or I just don't understand what is going on here). so here is code:
/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
uint64_t slash_hash(const char *s)
{
union {
uint64_t h;
uint8_t u[8];
} uu;
int i=0;
uu.h=strlen(s);
while (*s) { uu.u[i%8] += *s + i + (*s >> ((uu.h/(i+1)) % 5)); s++; i++; }
return uu.h; //64-bit
}
int main()
{
char *p[]={"pole","olep","mamao","omama"};
int j=0;
while(*(p+j)){
printf("%s\n",*(p+j));
j++;
};
for(int i=0;i<4;i++){
uint64_t var = slash_hash(p[i]);
printf("%lu \n",var);
}
return 0;
}
I expected it to print both the stings in the given array and then their hash index, but it only prints:
Upvotes: 0
Views: 56
Reputation: 104559
Your p
list is not guaranteed to be null terminated as you have it defined. Hence when j==5
, p[5]
is undefined and likely has garbage data. Hence while(*p+j))
is undefined behavior.
Instead of this:
char *p[]={"pole","olep","mamao","omama"};
int j=0;
while(*(p+j)){
printf("%s\n",*(p+j));
j++;
};
This (with some additinal cleanup for readability):
char *p[]={"pole","olep","mamao","omama", NULL}; // notice the NULL value at the end
int j=0;
while(p[j] != NULL) {
printf("%s\n",p[j]);
j++;
};
Upvotes: 1