c分段故障fgets [英] c segmentation fault fgets

查看:85
本文介绍了c分段故障fgets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main( int argc, char** argv) {

        FILE *inFilePtr = fopen(*(argv + 1), "r");
        char *rawdata = malloc(sizeof(char) * 100);
        float *ary = malloc(sizeof(float) * 50);
        int counter = 0;
        float averageAns;
        int count = 0;


        while (count < 1 ){
            //fgets(rawdata, 50, inFilePtr); //I have tried both
            fscanf(inFilePtr, "%s", rawdata);
            *(ary + counter) = atof(strtok(rawdata, ","));
             counter++;
            *(ary + counter ) = atof(strtok(rawdata, NULL));
            counter++;
            *(ary + counter) = atof(strtok(rawdata, NULL));
             counter++;
            count++;
        }

我无法为自己的一生弄清楚为什么我会不断出现段错误.即使没有循环,它也会断断续续(计数< 1只是为了查看我是否可以通过一次).

I cannot for the life of me figure out why I keep getting a seg fault. It will seg fault even without the loop (the count < 1 was just to see if I could make it through once).

它不适用于fgets(),fscanf().当我将fgets中的流更改为(stdin)时,它会出现故障,而我之所以这样提,是因为我认为文件*是问题所在,但现在我不认为这是问题.我已经在数据文件"和,"中创建了定界符.

It will not work with fgets(), fscanf(). It seg faults when I change the stream in fgets to (stdin), and I mention this because I assumed the file * was the issue, but now I do not think it is. I have made the delimiter in my data file " " and ",".

如果有人知道我做错了什么,我将不胜感激.

If anyone know's what I did wrong, I would appreciate it.

推荐答案

您对fscanf的调用肯定会失败,因为您没有提供输出参数.看起来应该像这样:

Your call to fscanf is guaranteed to fail, as you have not provided an output argument. It should look like:

fscanf(inFilePtr, "%s", rawdata);

您对strtok的呼叫也无效.要继续标记相同的字符串,strtok first 自变量应为NULLstrtok期望第二个参数仍然是有效的字符串.

Your calls to strtok are also invalid. To continue tokenising the same string, the first argument of strtok should be NULL; strtok expects the second argument to still be a valid string.

这些问题中的每一个都会单独导致段错误.为了将来简化调试,我建议您使用调试器并在要调试的语句后设置断点,或者注释掉可能期望进行segfault的其他行(如果包含代码,通常包括对字符串执行任何操作的任何内容)处于脆弱状态.

Each of these issues would cause a segfault on their own. To ease your debugging in future, I would suggest either using a debugger and setting a breakpoint after the statement you are debugging, or commenting out other lines which you might expect to segfault (which typically includes anything that does anything with strings, if your code is in a fragile state.

此外,作为样式问题,

*(ary + counter)

通常写

ary[counter]

这篇关于c分段故障fgets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆