c-为什么我会出现分段错误(核心转储)



我是一个C初学者。在经历了许多教程之后,我不确定为什么我会出现分割错误。我在函数write_new_file和search_by_firstname上都出现了此错误。我认为问题出在我的函数write_new_file中记录的参数类型PERSON*中。我已经尝试将它从指针更改为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. 您在中丢弃了一个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);
    

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

相关内容

  • 没有找到相关文章

最新更新