为什么我得到一个分段错误

为什么我得到一个分段错误

本文介绍了为什么我得到一个分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个程序,需要在一个明文文件,因为它的参数,并通过它分析,将所有的数字相加,然后打印出的总和。以下是我的code:

Hey guys I'm trying to write a program that takes in a plaintext file as it's argument and parses through it, adding all the numbers together and then print out the sum. The following is my code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

static int sumNumbers(char filename[])
{
    int sum = 0;
    FILE *file = fopen(filename, "r");
    char *str;

    while (fgets(str, sizeof BUFSIZ, file))
    {
        while (*str != '\0')
        {
            if (isdigit(*str))
            {
                sum += atoi(str);
                str++;
                while (isdigit(*str))
                    str++;
                continue;
            }
            str++;
        }
    }

    fclose(file);

    return sum;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Please enter the filename as the argument.\n");
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("The sum of all the numbers in the file is : %d\n", sumNumbers(argv[1]));
        exit(EXIT_SUCCESS);
    }

    return 0;
}

和我使用的文本文件是:

And the text file I'm using is:

这与一个相当枯燥的文本文件
  一些随机数散
  在整个吧。

下面一条是:87这里是另一个:3

Here is one: 87 and here is another: 3

和最后的最后两个数字:12
  19381.完成。唷。

and finally two last numbers: 12 19381. Done. Phew.

当我编译并尝试运行它,我得到一个分段错误。

When I compile and try to run it, I get a segmentation fault.

推荐答案

您还没有为缓冲区分配空间。结果指针 STR 只是一个悬空指针。所以,你的程序有效地转储从文件到内存中的位置,你没有自己读取数据,导致分段错误。

You've not allocated space for the buffer.
The pointer str is just a dangling pointer. So your program effectively dumps the data read from the file into memory location which you don't own, leading to the segmentation fault.

您需要:

char *str;
str = malloc(BUFSIZ); // this is missing..also free() the mem once done using it.

或者只是:

char str[BUFSIZ]; // but then you can't do str++, you'll have to use another
                  // pointer say char *ptr = str; and use it in place of str.

编辑:

还有一种错误的:

while (fgets(str, sizeof BUFSIZ, file))

第二参数应该是 BUFSIZ 不是的sizeof BUFSIZ

为什么?

由于第二参数是要读入缓冲区包括空字符的字符的最大数目。由于的sizeof BUFSIZ 4 您可以阅读最多高达 3 烧焦到缓冲区。这就是为什么 19381 正在读作 193 然后 81 lt;空&GT;

Because the 2nd argument is the maximum number of characters to be read into the buffer including the null-character. Since sizeof BUFSIZ is 4 you can read max upto 3 char into the buffer. That is reason why 19381 was being read as 193 and then 81<space>.

这篇关于为什么我得到一个分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 09:49