0

我试着做strcpy自己。它应该可以工作,我什至从某人在这里发布的关于 strcpy. 两者都给我一个“分段错误”。

char* strcpy(char * destination, const char * source)
{
    while( (*destination++ = *source++) != '\0' ) 
        ;
    return destination;
}

这段代码有什么问题?

char* a = "hello";
cout << strcpy(a, "Haha") << endl;
4

4 回答 4

6

您正在尝试覆盖字符串文字。这会导致未定义的行为。改为声明a为数组:

char a[] = "hello";

您的strcpy实现也有一个错误(假设是正常语义)。它应该返回一个指向目标缓冲区开头的指针,而不是结尾。

于 2013-05-21T18:33:51.663 回答
4

You are trying to write to data segment since "hello" is stored there.

Therefore, when you call strcpy you get segmentation fault.

Try:

char a[] = "hello";
cout << strcpy(a, "Haha") << endl;

instead.

EDIT: Inside your strcpy function, after the copy, destination will point to end of the string, you need to return beginning of the string instead.

于 2013-05-21T18:34:12.157 回答
3

a是指向字符串文字的指针:

char* a = "hello";

尝试修改字符串文字是未定义的行为。正如卡尔建议的那样,如果您使用字符串文字初始化一个数组,它将起作用:

char a[] = "hello" ;
于 2013-05-21T18:33:33.397 回答
3

Besides everything mentioned above and below about string literals, you're also returning a pointer to the END of your string, so even if you avoid the segmentation fault, you'll print "".

于 2013-05-21T18:35:36.123 回答