You need to enable JavaScript to run this app. 参考K&R示例写C语言哈希表:install段错误、printtable无输出排查
优惠活动
大模型
产品
解决方案
定价
更多

参考K&R示例写C语言哈希表:install段错误、printtable无输出排查

基于K&R教材实现哈希表的调试记录

编辑说明:我已更新init函数(代码已同步修改),改用malloc申请内存后,段错误(segmentation fault)问题已经消失,但此时printtable函数完全没有输出。后续根据大家的建议进一步修改代码后,目前代码已经可以正常运行。

我是C语言初学者,一直在跟随《C程序设计语言(K&R)》学习,参考其6.7节的哈希表示例实现了自定义哈希表(仅做了少量修改),以下是相关代码:

核心实现逻辑代码

#include <stdio.h>
#include <string.h>
#include "hashtable.h"

#define HASHSIZE 101


listptr * init_table()
{
    listptr *hashtab = (listptr *) calloc(HASHSIZE, sizeof(*hashtab));
    return hashtab;
}

unsigned hash (char *s)
{
    unsigned hashval;

    for (hashval=0; *s != '\0'; s++)
        hashval = *s + 31 * hashval;

    return hashval % HASHSIZE;
}

listptr lookup (listptr * hashtab, char *s)
{
    listptr np;

    for (np = hashtab[hash(s)]; np!=NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
            return np;
    return NULL;
}

listptr install(listptr * hashtab, char *name, char * defn)
{
    listptr np;

    unsigned hashval;

    if((np = lookup(hashtab, name)) == NULL) {
        np = (listptr) malloc(sizeof(*np));
        if (np==NULL || (np->name = strdup(name))==NULL)
            return NULL;

        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    }
    else
    {
        free((void*) np->defn);
    }
    if ((np->defn = strdup(defn)) == NULL)
        return NULL;

    return np;
}

void printtable(listptr * table, int len)
{
    listptr p;
    int i =0;
    while (i < len) {
        if (table[i] != NULL) {
            for (p = table[i];p!=NULL;p=p->next) {
                printf("%s\t%s\n", p->name, p->defn);
            }
        }
        i++;
    }
}

头文件hashtable.h内容

#ifndef HDR
#define HDR

#include <stdlib.h>

typedef struct nlist *listptr;

typedef struct nlist {
    listptr next;
    char *name;
    char *defn;
} Hashtablebucket;

listptr * init_table();
listptr lookup(listptr *, char *);
listptr install (listptr *, char *, char *);
void printtable(listptr *, int );

#endif

测试入口main.c代码

#include <stdio.h>
#include <string.h>
#include "hashtable.h"

int main()
{
    listptr * table = init_table();


    install(table, "key1", "value1");
    install(table, "key2", "value2");
    install(table, "key3", "value3");

    printtable(table, 101);

    return 0;
}

遇到的问题

  • 最初版本运行会触发段错误,当时以为已经为哈希表预留了101个元素的存储空间,没找到问题根因,希望获得调试帮助
  • 后续改用calloc初始化的版本运行时完全没有输出,需要帮忙排查问题

内容的提问来源于stack exchange,提问作者g0d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.24 05:24:05