You need to enable JavaScript to run this app. CS50x Speller开发Valgrind报映射权限错误段错误排查
优惠活动
大模型
产品
解决方案
定价
更多

CS50x Speller开发Valgrind报映射权限错误段错误排查

CS50x Pset5 Speller Valgrind段错误排查与修复

Valgrind报错片段

==395== Memcheck, a memory error detector
==395== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==395== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==395== Command: ./speller texts/cat.txt
==395== 
==395== 
==395== Process terminating with default action of signal 11 (SIGSEGV)
==395==  Bad permissions for mapped region at address 0x601DE8
==395==    at 0x401155: add_Node (dictionary.c:75)
==395==    by 0x401239: load (dictionary.c:107)
==395==    by 0x400944: main (speller.c:40)
==395== 
==395== HEAP SUMMARY:
==395==     in use at exit: 5,328,336 bytes in 95,140 blocks
==395==   total heap usage: 95,141 allocs, 1 frees, 5,332,432 bytes allocated
==395== 
==395== 552 bytes in 1 blocks are still reachable in loss record 1 of 2
==395==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==395==    by 0x5258E49: __fopen_internal (iofopen.c:65)
==395==    by 0x5258E49: fopen@@GLIBC_2.2.5 (iofopen.c:89)
==395==    by 0x4011BE: load (dictionary.c:88)
==395==    by 0x400944: main (speller.c:40)
==395== 
==395== 5,327,784 bytes in 95,139 blocks are still reachable in loss record 2 of 2
==395==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==395==    by 0x401118: add_Node (dictionary.c:69)
==395==    by 0x401239: load (dictionary.c:107)
==395==    by 0x400944: main (speller.c:40)
==395== 
==395== LEAK SUMMARY:
==395==    definitely lost: 0 bytes in 0 blocks
==395==    indirectly lost: 0 bytes in 0 blocks
==395==      possibly lost: 0 bytes in 0 blocks
==395==    still reachable: 5,328,336 bytes in 95,140 blocks
==395==         suppressed: 0 bytes in 0 blocks
==395== 
==395== For counts of detected and suppressed errors, rerun with: -v
==395== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Segmentation fault

现有代码实现

load函数

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    FILE *file = fopen(dictionary, "r");

    if (file == NULL)
    {
        return false;
    }

    // Set pointers in table to NULL
    for (int i = 0; i < N; i++)
    {
        table[i] = NULL;
    }
    
    char word[LENGTH + 1];  //to hold a word from dictionary
    
    while (fgets(word, LENGTH + 1, file) != NULL)
    {
        int row = hash(word);   // to determine where to store the word

        add_Node(row, word);
    }
    
    fclose(file);

    return true;
}

add_Node函数

// Adds new node to a list in dictionary
void add_Node(int row, char word[LENGTH + 1])
{
    node *newNode = malloc(sizeof(node));
    strcpy(newNode->word, word);
    
    if (table[row] == NULL)  //if single linked list is empty
    {
        table[row] = newNode;
    }
    else
    {
        node *tmpHead = table[row];   
        table[row] = newNode;
        newNode->next = tmpHead;
    }
}

问题定位

段错误触发在add_Node函数的table[row] = newNode行,核心原因是该地址不属于可写的table数组范围。
Valgrind报告的5MB左右的still reachable内存泄漏,是因为未实现unload函数释放哈希表节点,不属于本次段错误的触发原因。
常见的触发场景包括:

  • 哈希函数返回的row值为负数(无符号哈希值转int时溢出为负)或超出N的范围
  • N的定义值大于table数组的实际分配长度
  • fgets读取的内容包含换行符,导致哈希计算结果偏离预期边界
  • node结构体中word数组长度定义错误(未加1存字符串终止符),导致strcpy越界覆盖相邻内存
  • malloc分配失败未做校验,导致后续内存操作越界(本次报错排除该场景,因为strcpy已成功执行)

修复步骤

  1. 校验哈希索引合法性
    在add_Node开头增加边界检查,确认row处于0 <= row < N范围内,异常时打印对应word值定位问题:
    void add_Node(int row, char word[LENGTH + 1])
    {
        // 新增边界校验
        if (row < 0 || row >= N) {
            printf("Invalid row index: %d, word: %s\n", row, word);
            return;
        }
        node *newNode = malloc(sizeof(node));
        // 新增malloc返回值校验
        if (newNode == NULL) {
            return;
        }
        strcpy(newNode->word, word);
        if (table[row] == NULL)
        {
            table[row] = newNode;
            // 新增空链表场景下的next指针初始化,避免野指针
            newNode->next = NULL;
        }
        else
        {
            node *tmpHead = table[row];   
            table[row] = newNode;
            newNode->next = tmpHead;
        }
    }
    
  2. 清理fgets读取的换行符
    fgets会将文件中的换行符读入word数组,需在传给哈希函数前移除,避免干扰哈希计算:
    while (fgets(word, LENGTH + 1, file) != NULL)
    {
        // 移除末尾换行符
        int len = strlen(word);
        if (len > 0 && word[len - 1] == '\n') {
            word[len - 1] = '\0';
        }
        int row = hash(word);
        add_Node(row, word);
    }
    
  3. 确认哈希表与结构体定义一致性
    • 检查N的定义与全局table数组的实际长度完全匹配,避免出现定义不一致导致的越界:
      #define N 10000 // 与table数组长度一致
      node *table[N]; // 全局哈希表
      
    • 校验node结构体定义,确保word数组长度为LENGTH + 1,预留字符串终止符的存储空间:
      typedef struct node
      {
          char word[LENGTH + 1];
          struct node *next;
      } node;
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 12:45:07