guys,

I am implementing hash function in below code snippet but unfortunetly getting segmentation fault. Could you please help me to understand that what went wrong in this implementation.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>


unsigned long hash(char** str   )
    {
        unsigned long hash_val = 5381;
        unsigned long  sum=0;
        char* val ;
        int i,j;

        for ( j=0;j<9;j++)
        {  val=malloc(strlen(str[j])+1);
           memset(val,'\0',strlen(str[j])+1);
           strcpy(val,str[j]);
        for (i=0;val[i]!='\0';i++ )
           {

        sum=sum+val[i];


         }
       printf("%ld",sum);

        return sum;
    }

}

int main()
{

int i;
 char *str[9]={"mohan","ramesh","mohan","ramesh","cat","act","manish","vashsh","dfjdsj"};

unsigned long key;
for(i=0;i<9;i++)
{

key= hash(str[i]);
printf("\nkey[%ld]:val[%s]",key,str[i]);

}
return 1;
}

Edited 1 Year Ago by can-mohan: grammer

unsigned long hash(char** str )
char *str[9]={...
key= hash(str[i]);

One of these things is not like the others. If you're not compiling at the maximum warning level, you should turn it up now, because the compiler should point this out for you.

I'd also note that your hash algorithm is hideously inefficient and contains a memory leak.

Hi,

It is not inefficient algoritham as i am implementing like hash["abcd"]=hash["cbda"] so all the combination must have the same key value .apart from this i didn't understand about your resolution as not sure where are you pointing out the error in implementation.

warning should be on always it is true. After doing (changes in makefile) this below changes makes code perfectly fine.
(1)

unsigned long hash(char *str)

(2)

for ( j=0;j<9;j++)
        {  val=malloc(strlen(str)+1);
           memset(val,'\0',strlen(str)+1);
           strcpy(val,str);
        for (i=0;val[i]!='\0';i++ )
           {

        sum=sum+val[i];


         }

Apart from this instead of sum , I am going to return the

T%sum

where T is the size of Hash table.

Edited 1 Year Ago by can-mohan: code formatting

This question has already been answered. Start a new discussion instead.