通过运行时传递输入时获取分段错误

时间:2016-11-08 03:47:08

标签: c pointers segmentation-fault

int main(int argc, char* argv) {

    struct student_record_node *head;
    char *filename = argv[1];
    printf("%s",filename);
    parseFile(filename,&head);
    return (0); 
}

struct student_record_node* student_record_allocate() 
{
    struct student_record_node *newNode;
    newNode =  malloc(sizeof (struct student_record_node));
    return newNode;
}

void parseFile(char *filename, struct student_record_node**head) 
{
    FILE *fp=NULL;
    char fname[21], flast[21];
    int id,age;
    int ret;

    /*creates a POINTER to "filename"*/
    fp = fopen(filename, "r+");
    if (fp== NULL) {
        printf("No such file\n");
        exit(1);
    }
    printf("%s",fp->_tmpfname);

    while (fp) {
        struct student_record_node *new_student;
        new_student = student_record_allocate();
        fscanf(fp,"%s %s %d %d",new_student->record_->first_name_ , new_student->record_->last_name_,new_student->record_->student_id_, new_studen    t->record_->student_age_);
        new_student->next_ = NULL;
        if (*head == NULL)
            *head=new_student;
        else {
            struct student_record_node *temp = *head;
            while (temp->next_ != NULL) {
                temp = temp->next_;
            }
            temp->next_=new_student;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我在您的代码中看到了一些问题: -

  1. 内存分配问题。在你的情况下,你没有将struct *转换为struct student_record_node。正如malloc返回void *
  2. 你为什么在while循环中使用fp?如果您成功打开文件,您将获得指向文件的有效指针(fp),并且您将处于无限循环状态。
  3. 由于你没有发布结构声明,我只能说first_name_和last_name_没有定义为arrey,那么你需要为这些变量分配内存。