You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HackerRank C语言动态数组题提交后出现segmentation fault调试求助

问题诊断与修复方案

核心错误点

  • 内存未初始化:malloc() 分配的堆内存是未初始化的,存储的是随机垃圾值。你代码中依赖 total_number_of_pages[x][index] == 0 判断空位、对 total_number_of_books[x] 直接自增的逻辑,都会因为初始值异常出现逻辑错误,甚至直接越界访问内存触发段错误。
  • total_number_of_books 分配冗余:该数组只需要为每个书架存储1个图书总数,仅需要分配 总书架数 * sizeof(int) 的空间即可,你额外乘的1100属于不必要的冗余,虽然不会直接导致段错误,但属于内存浪费。
  • 空位查找逻辑冗余:你不需要循环查找空位,total_number_of_books[x] 本身就存储了当前书架的图书总数,下一本要插入的下标就是total_number_of_books[x],完全不需要循环遍历,效率极低还容易出错。

修复后的完整代码

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

/*
 * 存储每个书架上的图书总数
 */
int* total_number_of_books;

/*
 * 存储每个书架上每本书的页数,行对应书架,列对应图书
 */
int** total_number_of_pages;

int main()
{
    int total_number_of_shelves;
    scanf("%d", &total_number_of_shelves);

    int total_number_of_queries;
    scanf("%d", &total_number_of_queries);

    // 修正:total_number_of_books只需要总书架数个int空间,分配后初始化为0
    total_number_of_books = (int *)malloc(sizeof(int) * total_number_of_shelves);
    memset(total_number_of_books, 0, sizeof(int) * total_number_of_shelves);

    total_number_of_pages = (int **)malloc(sizeof(int*) * total_number_of_shelves);
    // 修正:每个书架初始分配空间,用calloc直接初始化内存为0,避免垃圾值
    for (int tnos=0; tnos<total_number_of_shelves; tnos++) {
        total_number_of_pages[tnos] = (int *)calloc(1100, sizeof(int));
    }

    while (total_number_of_queries--) {
        int type_of_query;
        scanf("%d", &type_of_query);
        
        if (type_of_query == 1) {
            int x, y;
            scanf("%d %d", &x, &y);
            // 修正:直接用total_number_of_books[x]作为插入下标,不需要循环找空位
            int insert_idx = total_number_of_books[x];
            total_number_of_pages[x][insert_idx] = y;
            total_number_of_books[x]++;    
        } else if (type_of_query == 2) {
            int x, y;
            scanf("%d %d", &x, &y);
            printf("%d\n", *(*(total_number_of_pages + x) + y));
        } else {
            int x;
            scanf("%d", &x);
            printf("%d\n", *(total_number_of_books + x));
        }
    }

    if (total_number_of_books) {
        free(total_number_of_books);
    }
    
    for (int i = 0; i < total_number_of_shelves; i++) {
        if (*(total_number_of_pages + i)) {
            free(*(total_number_of_pages + i));
        }
    }
    
    if (total_number_of_pages) {
        free(total_number_of_pages);
    }
    
    return 0;
}

关键优化说明

  1. 用calloc替代malloc分配图书页数数组,自动将内存初始化为0,避免垃圾值干扰逻辑。
  2. 用memset将书架图书总数数组初始化为0,保证计数从0开始。
  3. 移除了冗余的空位查找循环,直接用已有计数作为插入下标,逻辑更简洁效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:18:01