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

家住魔仙堡 提交于 2019-12-11 07:37:04

问题


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);
}

回答1:


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;


来源:https://stackoverflow.com/questions/44856233/why-is-this-c-code-getting-a-bus-error-no-external-functions-allowed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!