Hashing of small dictionary

若如初见. 提交于 2020-05-31 03:46:08

问题


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;
        }
    }
}

回答1:


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);
}


来源:https://stackoverflow.com/questions/61890233/hashing-of-small-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!