user13279908
user13279908

Reputation: 25

Hashing of small dictionary

I want to hash small dictionary ("dictionaries/small"). Main file compiles correctly, but at runtime it produces "Segmentation fault" message with function insert() (specifically something wrong with malloc(), but I don`t know what).

HASH.c

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

typedef struct node
{
    char* name;
    struct node* next;
}
node;

node* first[26] = {NULL};

int hash(const char* buffer)
{
    return tolower(buffer[0]) - 'a';
}

void insert(int key, const char* buffer)
{
    node* newptr = malloc(sizeof(node));
    if (newptr == NULL)
    {
        return;
    }

    strcpy(newptr->name, buffer);
    newptr->next = NULL;

    if (first[key] == NULL)
    {
       first[key] = newptr;
    }
    else
    {
        node* predptr = first[key];
        while (true)
        {
            if (predptr->next == NULL)
            {
                predptr->next = newptr;
                break;
            }
            predptr = predptr->next;
        }
    }
}

Upvotes: 1

Views: 41

Answers (1)

Roberto Caboni
Roberto Caboni

Reputation: 7490

In function insert() you correctly allocate the new node:

node* newptr = malloc(sizeof(node));

In this way you make room for a full struct node: a pointer to node and a pointer to char. But you don't allocate the space where those pointer are supposed to point.

So, when you copy the input buffer within name field, you are performing an illegal attempt to write to a char * pointer that has not been allocated and not even initialized:

strcpy(newptr->name, buffer);

All pointers need to be allocated (or at least initialized to a valid memory location) before writing in them. In your case:

newptr->name = malloc( strlen( buffer ) + 1 );
if( newptr->name )
{
    strcpy(newptr->name, buffer);
}

Upvotes: 1

Related Questions