【问题标题】:Getting segmentation error while passing input through runtime通过运行时传递输入时出现分段错误
【发布时间】:2017-03-21 14:09:09
【问题描述】:
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;
        }
    }
}

【问题讨论】:

  • 我不认为这是 C++
  • 是的,但任何逻辑上的帮助都会受到重视。
  • fscanf(fp,"%s %s %d %d", ... 是错误的。 1)new_student->record_ 未初始化(不指向记录对象)。 2) new_student->record_->student_id_ --> &new_student->record_->student_id_
  • while (fp) { : fp 总是正确的。
  • 我这样做了,我得到了同样的错误。

标签: c pointers segmentation-fault


【解决方案1】:

我在您的代码中发现了一些问题:-

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多