0

PLease Someone help me I was trying to implement a hash table that stores the word of English language for pset 5. So to be in brief, I used an array of linked list ( Chaining ) , I haven't made the entire program but just implemented so that It takes a single word input and searches it through the hash table but it starts giving me Segmentation fault. Please help me on this one.... Thank you in advance !

strcpy(new->s,val);

This is the line where I got stuck with the Segmentation Fault.

My entire code :

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

typedef struct node
{
string s;
struct node *next;
}node;

node* create(char*);

unsigned long sdbm(unsigned char*);

bool search(string s,node *first)
{
node *ptr=first;
bool found=false;

while(ptr->next!=NULL)
{
    if(strcmp(ptr->s,s)==0)
    {
        found=true;
        break;
    }

}

if(found==true)
return true;
else
return false;
}



int main(void)
{
node a[26];
printf("Enter the string\n");
string s=get_string();
unsigned long hashcode = sdbm((unsigned char*)s);
printf("The hashcode is %lu\n", hashcode);

a[hashcode].next=create(s);

printf("Enter the string to be searched among the ones you recently typed 
in\n");
string t=get_string();

if(search(t,&a[sdbm((unsigned char*)t)]) == true)
printf("found\n");
else
printf("not found\n");

}


node* create(string val)
{
node* new = malloc(sizeof(node));
if(new!=NULL)
{
    new->s="";

    strcpy(new->s,val);   // this is the part ehere I get Segmentation Fault
    new->next=NULL;
}

return new;

}

unsigned long
sdbm(unsigned char *str)
{
    unsigned long hash = 0;
    int c;

    while ((c = *str++)!=0)
        hash = c + (hash << 6) + (hash << 16) - hash;

    return hash%26;
}
1
new->s="";

lets new->s point to an empty string stored in a read-only area.

strcpy(new->s,val);

then tries to write to that read-only area.

You need writable memory associated to the pointer. You could for example declare it as char s[LENGTH+1]; in the struct (LENGTH is declared in dictionary.h and is the length of the longest word to consider).

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .