1

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);
}
  • 4
    Do not try to change the string literal. – BLUEPIXY Jul 01 '17 at 00:09
  • 2
    Try `pooch = "allo";` --> `pooch = (char[]){"allo"};` or `char *pooch; pooch = "allo"` --> `char pooch[] = "allo"` – BLUEPIXY Jul 01 '17 at 00:11
  • 1
    In C++11 and maybe C11(though i'm not sure), non const pointers to string literals are deprecated (make sure you're using the latest version of your compiler, and with compiler warnings on). Anyway, just remember that trying to write to memory allocated for a string literal is illegal and will result in undefined behaviour. – George Jul 01 '17 at 00:17
  • @EatABagel For each source string with different number of symbols you have to write a separate function.:) – Vlad from Moscow Jul 01 '17 at 00:20
  • How can I make this char pooch[] = "allo" in 2 lines, so to separate the declaration from the initialization? – WhoAteTheCake Jul 01 '17 at 00:23
  • Possible duplicate of [Bus error 10 in C: string literals](https://stackoverflow.com/questions/32664826/bus-error-10-in-c-string-literals) – Raymond Chen Jul 01 '17 at 00:54
  • Why would you want to separate declaration from initialization? It's easier when you combine them. If you must, then `char pooch[16]; strcpy(pooch, "allo");` or variations on that them. You have to specify the size of the array (you could use `sizeof("allo")` instead of 16; 16 is deliberately over-allocating space), and then you have to copy data into it (so you need to include `` too). So much easier just to say `char pooch[] = "allo";`. – Jonathan Leffler Jul 01 '17 at 06:34

1 Answers1

2

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;
anneb
  • 5,510
  • 2
  • 26
  • 26
  • 1
    The OP was clear about **_no external functions allowed_**. – alvits Jul 01 '17 at 00:47
  • 2
    `pooch` can be initialised using `char pooch[] = "allo"`. In that case, the string literal is used to initialise the array, but the array ca be modified. – Peter Jul 01 '17 at 01:03