【问题标题】:How to clear 'segmentation fault (core dumped)' in while loop如何在while循环中清除“分段错误(核心转储)”
【发布时间】:2019-10-04 17:45:25
【问题描述】:

enter code here这只是我的代码的一部分,但是在使用调试程序后,我能够缩小分段错误来自在 while 循环中访问 i 的范围。

这是输入数据:

30218294 Super Man 2.9
39324809 Spider Man 3.5
48201093 Papa Smurf 1.9
39482010 Mickey Mouse 3.2
49384832 Minnie Mouse 3.4
-1

我尝试在循环之前设置i = 0 并更改while 循环的条件。

#include <stdio.h>
#include <cstring>
#include <string.h>
#include <stdlib.h>

struct student{
    char fname[100];
    char lname[100];
    int euid;
    float gpa;
};

/* Reads the data from a file and stores it in the array of structs */
void readData(struct student *db, int *size)
{
    const char* file_name = "input";

    FILE *infile;
    infile=fopen(file_name,"r");

    int i=0, euid;
    fscanf(infile,"%d",&euid);
    while(euid > 0){
        db[i].euid = euid; //**ERROR: Segmentation Fault**
        fscanf(infile,"%s%s%f%d",db[i].fname,db[i].lname,&db[i].gpa,&euid);
        i++;
    }
    fclose(infile);
    *size = i;
}

int main(void)
{

    int size;
    struct student* db[100];

    /* read info from file */
    readData(*db,&size);

    return 0;
}

程序收到信号SIGSEGV,分段错误。 func.c:17 处 readData (db=0xb7fe173d, size=0xbffff278) 中的 0x00400729 17 db[i].euid = euid;

【问题讨论】:

  • 你没有初始化iint i 不会将 i 的值设置为零。
  • 还有 db 指向的空间吗?
  • 是的,它是一个结构 student struct student{ char fname[100];字符 lname[100];诠释 euid;浮动gpa; };
  • 我的猜测是db要么没有初始化,要么不够大,要么为空。
  • 我是否也将 euid 设置为一个值?如果是这样,是什么?

标签: c arrays segmentation-fault


【解决方案1】:

在这个节目中

int main(void)
{

    int size;
    struct student* db[100];

    /* read info from file */
    readData(*db,&size);

    return 0;
}

*db 等价于db[0],因此未初始化的指针值被传递给readData

要读入一个静态分配在main中的数组,程序应该是这样的:

int main(void)
{

    int size;
    /* allocate array of the struct, not array of "pointer to" the struct */
    struct student db[100];

    /* read info from file */
    /* remove "*" so that the pointer to the first element will be passed */
    readData(db,&size);

    return 0;
}

添加检查fopenfscanfs是否成功将使您的程序更好。

【讨论】:

    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2021-06-03
    相关资源
    最近更新 更多