为什么我会出现Segmentation fault(core dumped)?

时间:2015-02-10 20:26:41

标签: c segmentation-fault binaryfiles fwrite fread

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

//------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 个答案:

答案 0 :(得分:1)

  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分配空间,在这里您尝试访问temp

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

    但你没有为它分配空间,你也不需要指针,而是

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

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