为什么我得到EXC_BAD_ACCESS?

sha*_*ind 0 c exc-bad-access

我想反转一个字符串,但我在swap char上出错了.

有人可以帮我吗?

char*  reverse_char(char* src){
    char *p,*q;
    p = q = src;
    while(*(p) != '\0'){
        p++;
    }
    p--;

    char  temp = '\0';
    while (p > q) {
        temp = *p;
        *p = *q; // I got exec bad access here ??? why 
        *q = temp;
        p--;
        q++;
    }
    return src;
}
Run Code Online (Sandbox Code Playgroud)

这是主要方法.

int main(int argc, char const* argv[])
{
    char *hi = "hello world!\n";
    printf("%s", hi);

    reverse_char(hi);
    printf("%s", hi);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*ain 6

替换char *hi = "hello world!\n";char hi[] = "hello world!\n";

"hello world!\n"是字符串文字,可能无法写入导致访问错误.修改字符串文字的内容是未定义的行为,它可能会静默写入内容,引发访问错误或者可能会执行其他意外操作.(所以你不应该写字符串文字)

加起来

char a[] = "...";  /* Contents of a can be assigned */
char *a = "...";   /* Writing to contents of memory pointed by a leads to UB */
Run Code Online (Sandbox Code Playgroud)