为什么会出现分段错误? [英] Why am I getting a segmentation fault?

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

问题描述

我正在尝试编写一个程序,该程序将纯文本文件作为参数并对其进行解析,将所有数字相加,然后打印出总和.以下是我的代码:

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 != '')
        {
            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.
");
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("The sum of all the numbers in the file is : %d
", sumNumbers(argv[1]));
        exit(EXIT_SUCCESS);
    }

    return 0;
}

我使用的文本文件是:

这是一个相当无聊的文本文件一些散落的随机数贯穿其中.

This a rather boring text file with some random numbers scattered throughout it.

这是一个:87,这是另一个:3

Here is one: 87 and here is another: 3

最后两个数字:1219381. 完成.唷.

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.

The 2nd argument should be BUFSIZ not sizeof BUFSIZ.

为什么?

因为第二个参数是要读入缓冲区的最大字符数,包括空字符.由于 sizeof BUFSIZ4 您可以将最大 3 字符读取到缓冲区中.这就是为什么 19381 被读取为 193 然后是 81.

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>.

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

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