为什么会出现分段错误(核心已转储)?

Why do I get Segmentation fault (core dumped)?

我是C初学者。在阅读了许多教程之后,我不确定为什么会出现分段错误。我的函数 write_new_file 和 search_by_firstname 都出现了这个错误。我认为问题在于我的函数 write_new_file 中的参数类型 PERSON *inrecord。我已经尝试将其从指针更改为 inrecord 并相应地更改所有变量,但问题仍然存在。我已经问过 class 的伙伴,但还没有解决方案。

//------TYPEDEFS------
typedef struct{
    char firstname[20];
    char famname[20];
    char pers_number[13]; //yyyymmddnnnc
}PERSON;

void write_new_file(PERSON *inrecord){
    FILE *ptr_myfile;
    ptr_myfile=fopen("test.bin","w");
    if (ptr_myfile==NULL)
    {
        printf("Unable to open file!");
        exit(0);
    }
    strcpy(inrecord->firstname,"Name",20);
    strcpy(inrecord->famname, "surname",20);
    strncpy(inrecord->pers_number, "880192234",13);
    fwrite(&inrecord, sizeof(PERSON), 1, ptr_myfile);
    fclose(ptr_myfile);

}
void search_by_firstname(char *name){
    FILE *ptr_myfile;
    ptr_myfile=fopen("test.bin","r");
    PERSON *temp=NULL;
    if (ptr_myfile==NULL)
    {
        printf("Unable to open file!");
        exit(0);
    }

        fread(temp,sizeof(PERSON),1,ptr_myfile);
        if(strcmp(temp->firstname,name)!=0){
            printf("Not found");
            }else{
               printf("found");
            }

    fclose(ptr_myfile);
}

int main(void){
    PERSON *ppost=NULL;
    write_new_file(ppost);
    search_by_firstname("Neda");
    return(0);
}
  1. 您取消引用 NULL 指针,在

    void write_new_file(PERSON *inrecord)
    {
        FILE *ptr_myfile;
    
        ptr_myfile = fopen("test.bin","w");
        if (ptr_myfile == NULL)
        {
            printf("Unable to open file!");
            exit(0);
        }
        strcpy(inrecord->firstname, "Name", 20);
        strcpy(inrecord->famname, "surname", 20);
        strncpy(inrecord->pers_number, "880192234", 13);
        fwrite(&inrecord, sizeof(PERSON), 1, ptr_myfile);
        fclose(ptr_myfile);
    }
    

    你不需要传递一个指向写文件函数的指针,你需要的是

    void write_new_file()
    {
        FILE *ptr_myfile;
        PERSON person;
    
        ptr_myfile = fopen("test.bin","w");
        if (ptr_myfile == NULL)
        {
            printf("Unable to open file!");
            exit(0);
        }
        strcpy(person.firstname, "Name", 20);
        strcpy(person.famname, "surname", 20);
        strncpy(person.pers_number, "880192234", 13);
    
        fwrite(&person, sizeof(PERSON), 1, ptr_myfile);
    
        fclose(ptr_myfile);
    }
    

    在你的主要任务中你会这样做

    int main(void) {
        write_new_file();    
        search_by_firstname("Neda");
        return(0);
    }
    
  2. 你没有为temp分配space,这里你试图访问temp

     fread(temp,sizeof(PERSON),1,ptr_myfile);
    

    但是你没有为它分配space,这里你也不需要指针,而是

     PERSON temp;
     fread(&temp, sizeof(PERSON), 1, ptr_myfile);
    

    会做得更好,您可能还想检查 fread() 是否成功,然后再尝试取消引用 temp,否则会导致未定义的行为。