Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segmentation Fault while working on a Hash Table

I am just learning c with the cs50 course and I just got introduced to pointers and data structures (It is very confusing please help). So I got a project where I need to make a hash table and I started first by trying to add some nodes to the zero index of the list instead of going for hash table right away and for some reason I am getting a segmentation fault while adding the node to the list. Its on line 31 (which is n->next = table[0]->next;) I am not able to understand why is this happening. Someone please help and thanks in advance

LoL I just forgot to add the code

Here It Is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

int main(void)
{
    typedef struct node
    {
        char *word;
        struct node *next;
    } node;

    const unsigned int N = 10;
    node *table[N];

    for (int i = 0; i < 10; i++)
    {
        table[i] = NULL;
    }

    char *words[] = {"Hell", "Sup", "Brain", "Greek", "Mother", "Flip", "Poster", "Dark", "Apple", "Kandy"};

    for (int i = 0; i < 10; i++)
    {
        char *wordle = words[i];

        node *n = malloc(sizeof(node));
        n->word = wordle;

        n->next = table[0]->next;
        table[0]->next = n;

        printf("%s\n", table[0]->next->word);
    }
}

>Solution :

You are initializing all table elements to NULL, and later you attempt to access the first (null) element: table[0]->next. This will result in dereferencing a null pointer, hence the segmentation fault you got.

What you need to do is allocating a node for each table entry:

for (int i = 0; i < N; i++) // You didn't make N constant for no reason, did you?
{
    table[i] = malloc(sizeof(node));
}

Edit:

You can improve/optimise your code by avoiding repetitive calls to malloc() (as @Lundin suggested):

node* table = calloc(N, sizeof(node));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading