WhoAteTheCake
WhoAteTheCake

Reputation: 53

Why is this C code getting a bus error? (No external functions allowed)

I've been working through this code for hours but couldn't locate the error. It passes the compiler, but while running it gets a bus error, why?

char    *ft_strrev(char *str);

char    *ft_strrev(char *str)
{
    int i;
    int count;
    int d;
    char temp[5];

    i = 0;
    count = 0;
    d = 0;
    while (str[count] != '\0')
    {
        count++;
    }
    while (d < count)
    {
        temp[d] = str[d];
            d++;
    }
    while (--count >= 0)
    {
        str[i] = temp[count];
        i++;
    }
    return (str);
}

int main()
{
    char *pooch;
    pooch = "allo";
    ft_strrev(pooch);
    return (0);
}

Upvotes: 1

Views: 318

Answers (1)

anneb
anneb

Reputation: 5768

Your function is modifying the string. In the code you pass in a literal string. You should not change literal strings.

Instead use something like:

char pooch[5];
pooch[0] = 'a';
pooch[1] = 'l';
pooch[2] = 'l';
pooch[3] = 'o';
pooch[4] = 0;
ft_strrev(pooch);
return 0;

Upvotes: 2

Related Questions