是什么导致我的 C 程序出现此错误(分段错误(核心已转储))?

What is causing this error in my C program (Segmentation fault (core dumped))?

我正在尝试创建一个小程序(我还是个初学者),它将根据输入的一段文本中字母(大写或小写)的出现频率创建直方图一个论点。

不幸的是,由于某种原因,它在执行 a.out 文件时一直给我一个 Segmentation fault (core dumped) 错误。

#include <unistd.h>

void    ft_putchar(char c)
{
    write(1, &c, 1);
}

void    letter_count(char *str)
{
    int     i;
    int     count;
    char    letter;

    i = 0;
    count = 0;
    letter = 'a';
    while (str[i])
    {
        if (str[i] >= 'A' && str[i] <= 'Z')
            str[i] += 32;
        i++;
    }
    i = 0;
    while (letter <= 'z')
    {
        while (str[i])
            if (str[i++] == letter)
                count++;
        ft_putchar(letter);
        ft_putchar(' ');
        while (count-- > 0)
            ft_putchar('|');
        ft_putchar('\n');
        i = 0;
        count = 0;
        ++letter;
    }
}

int main(int argc, char **argv)
{
    if (argc == 2)
        letter_count(argv[2]);
    else
        write(1, "Error\n", 6);
    return (0);
}
if (argc == 2)
    letter_count(argv[2]);

错了。如果 argc 为 2,则表示有两个参数,即 argv[0]argv[1]

所以试试

    letter_count(argv[1]);

顺便说一句:当 argc 为 2 时 argv[2] 为 NULL