问题
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