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

C语言实现数据库时log_init函数触发段错误问题求助

代码问题诊断与修复方案

核心错误原因

你代码的段错误本质是指针类型误用导致的非法内存解引用,和宏N的赋值无关:

  • 你在main里用malloc申请的log是log_t*类型,指向一块连续存储log_t结构体的数组,正确的成员访问语法是log[下标].id
  • 但你在init_log、printList函数里,把传入的二级指针cat(也就是log的地址)当成了log_t*类型的指针数组来用,cat[index->sarcount]->id的写法相当于把数组里存储的结构体值强行当成指针解引用,前两次可能刚好踩到合法内存区域,第三次必然触发非法访问段错误。

其他存在的问题

  • 未初始化index_t的sarcap字段,也没有做插入前的容量边界检查,插入日志数超过N时会出现数组越界
  • 函数参数设计冗余:没有扩容逻辑的前提下,init_log和printList不需要传入二级指针
  • printList声明返回int类型,但函数内没有返回值,属于语法不规范

修复后的代码示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10 //可自行调整初始容量
#define STRLIM 30 

typedef struct log{
    int id;
}log_t;

typedef struct index{
    int sarcount;
    int sarcap; //存储当前日志数组最大容量
}index_t;

// 调整为一级指针参数
log_t* init_log(log_t* cat,index_t* index);
int printList(log_t* cat,index_t* index);
int menu(void);

log_t* init_log(log_t* cat,index_t* index){
    // 先做容量边界检查
    if (index->sarcount >= index->sarcap) {
        printf("日志容量已满,插入失败\n");
        return cat;
    }
    // 正确的数组成员访问语法
    cat[index->sarcount].id = index->sarcount;
    index->sarcount++;
    return cat;
}

int menu(void){
    printf("1. Insert a new log\n");
    printf("5. Exit\n");   
    printf("6. Print the list\n");
    return 0;
}

int printList(log_t* cat,index_t* index){
    int i=0;
    for(i=0;i<index->sarcount;i++){
        printf("#%d ID:%d\n",i,cat[i].id);
    }
    return 0; //补充返回值
}

int main(int argc, char const *argv[])
{  
    log_t* log = malloc(sizeof(log_t)*N);
    if(!log){
        perror("failed to malloc:");
        exit(EXIT_FAILURE);
    }
    index_t* index = malloc(sizeof(index_t));
    index->sarcount = 0;
    index->sarcap = N; //初始化容量字段

    int choice=0;
    while(1){
        menu();
        scanf("%d", &choice);
        if(choice==1){
            printf("enter a log\n");     
            log = init_log(log,index);  
        }
        else if(choice==5){
            printf("exiting now\n");
            // 释放申请的内存避免泄漏
            free(log);
            free(index);
            exit(0);
        }
        else if(choice==6){
            system("clear");
            printf("printing all existing logs:\n");
            printList(log,index);
        }
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:27:04