为什么char-value-copy赢了';你不能在OSX中工作吗?

为什么char-value-copy赢了';你不能在OSX中工作吗?,c,C,这是教科书上的C代码 void strcpy_new(char *s, char *t) { while ((*s = *t) != '\0') { s++; t++; } } int main(int argc, const char * argv[]) { char *s = "this is line a"; char *t = "this is line b"; printf("%s", s); strc

这是教科书上的C代码

void strcpy_new(char *s, char *t) {
    while ((*s = *t) != '\0') {
        s++;
        t++;
    }
}

int main(int argc, const char * argv[])
{

    char *s = "this is line a";
    char *t = "this is line b";
    printf("%s", s);
    strcpy_new(s, t);
    printf("%s", s);
    return 0;
}

当我用Xcode运行它时,我得到了EXEC\u BAD\u访问权。

获得EXEC\u BAD\u访问权的原因是那些字符串文本
“这是行a”
“这是行b”
存储在只读内存中。尝试写入(
*s=*t
)是未定义的行为,因此您将收到一个崩溃

要纠正此代码,您应该为
s
分配一些内存,使其足够大以容纳第二个字符串(
t
):


问题是覆盖字符串文字的效果未定义

char *s = "this is line a";
char *t = "this is line b";
strcpy_new(s, t);

s
t
在代码的数据部分都处于关闭状态,当您尝试更改它们时,您的特定设置恰好为您提供了一个
EXEC\u BAD\u访问权限。

我敢打赌,您正在尝试使用一个字符串文本的目标运行
strcpy\u new

#include <string.h>

int main(int argc, char *argv[])
{
    char *a = "Some String";
    char *b = "Another string";
    strcpy(b, a);
    return 0;
}
#包括
int main(int argc,char*argv[])
{
char*a=“一些字符串”;
char*b=“另一个字符串”;
strcpy(b,a);
返回0;
}
将给执行者错误的访问权限。然而,下面的内容不会

#include <string.h>

int main(int argc, char *argv[])
{
    char *a = "Some String";
    char b[] = "Another string";
    strcpy(b, a);
    return 0;
}
#包括
int main(int argc,char*argv[])
{
char*a=“一些字符串”;
字符b[]=“另一个字符串”;
strcpy(b,a);
返回0;
}

不同之处在于,在第一种情况下,
b
指向可执行文件的
\uuuuuu文本、\uuuuu cstring、cstring\u literals
部分中的内存块,该部分受写保护。在第二种情况下,它指向堆栈上的内存块。

字符串文字是只读的。这里有一个很好的答案:

C中的字符串文字是只读的。在示例代码中,“我的字符串”是字符串文字

str[]声明将文本复制到可写内存(堆栈或堆)中。因此,您的程序可以修改字符串


*声明初始化指向文本本身的指针,因此您有一个指向只读段的指针。如果您试图覆盖它,您将获得SEGV。

显示如何调用
strcpy\u new
我用完整的代码编辑了我的问题
#include <string.h>

int main(int argc, char *argv[])
{
    char *a = "Some String";
    char b[] = "Another string";
    strcpy(b, a);
    return 0;
}