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; }
关键优化说明
- 用
calloc替代malloc分配图书页数数组,自动将内存初始化为0,避免垃圾值干扰逻辑。 - 用
memset将书架图书总数数组初始化为0,保证计数从0开始。 - 移除了冗余的空位查找循环,直接用已有计数作为插入下标,逻辑更简洁效率更高。
内容的提问来源于stack exchange,提问作者user17007422
相关产品推荐
相关产品推荐

