问题
I tried to make strcpy
myself. It should work, I even copied and pasted the (almost exact code) from someones post here about strcpy
. Both give me a "Segmentation Fault".
char* strcpy(char * destination, const char * source)
{
while( (*destination++ = *source++) != '\0' )
;
return destination;
}
What's wrong with this code?
char* a = "hello";
cout << strcpy(a, "Haha") << endl;
回答1:
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.
回答2:
You're trying to overwrite a string literal. That causes undefined behaviour. Declare a
as an array instead:
char a[] = "hello";
Your strcpy
implementation has a bug, too (assuming the normal semantics). It should return a pointer to the beginning of the destination buffer, not the end.
回答3:
a
is a pointer to a string literal:
char* a = "hello";
Trying to modify a string literal is undefined behavior. As Carl suggested, if you initialize an array with the string literal instead it will work:
char a[] = "hello" ;
回答4:
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 "".
来源:https://stackoverflow.com/questions/16677015/whats-wrong-with-my-strcpy