简体   繁体   中英

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

I'm trying to create a little program (I'm still a beginner) which will create a histogram based on how frequent a letter of the alphabet (uppercase or lowercase) is found in a piece of text entered as an argument.

Unfortunately, for some reason it keeps giving me a Segmentation fault (core dumped) error when executing the a.out file.

#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]);

is wrong. If argc is 2, it means that there are two arguments, ie argv[0] and argv[1]

So try

    letter_count(argv[1]);

BTW: When argc is 2 then argv[2] is NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM