Why does this code crash? Is strcpy not being used properly?
Asked
Active
Viewed 1,997 times
-2

Vlad from Moscow
- 301,070
- 26
- 186
- 335

Moshe Erlbaum
- 29
- 4
-
2[Please don't post images of code or error messages.](http://meta.stackoverflow.com/q/303812/1679849) – r3mainer Nov 25 '16 at 01:06
-
1Possible duplicate of [Program aborts when using strcpy on a char pointer? (Works fine on char array)](http://stackoverflow.com/questions/5645949/program-aborts-when-using-strcpy-on-a-char-pointer-works-fine-on-char-array) – Crowman Nov 25 '16 at 01:08
-
2Possible duplicate of [What is the difference between char s\[\] and char \*s in C?](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c) – r3mainer Nov 25 '16 at 01:09
1 Answers
4
The variable msg1
points to the memory occupied by a string literal. String literals are not modifiable. Any attempt to modify a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
- It is unspecified whether these arrays are distinct provided their elements > have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
Take into account that if you want to copy a string to a character array using the standard C function strcpy
then the array has to have enough memory to accommodate the string including its terminating zero.
You can make your code valid by substituting the pointer for a character array. For example
char msg1[15] = "Hello World";
//...
strcpy( msg1, "Hello New York" );

Vlad from Moscow
- 301,070
- 26
- 186
- 335