In the first example the pointer t
is made to point to a string constant "Hello"
, and then immediately afterwards to the string constant "World"
; the latter value is then printed.
The code in the second example crashes with segfault, because string constants are not writeable. (strcpy tries to modify the memory that holds the text "Hello"
). GCC places string constants into a read-only section, unless compiled with -fwriteable-strings
.
The code
char *test = "Hello";
means that the compiler+linker place a string of bytes "Hello\0" in a read-only section, and the test
points into the first character thereof. Any attempt to write through this pointer would be harshly punished by the operating system.
On the other hand
char test[] = "Hello";
declares an array of 6 characters, with initial value of ({ 'H', 'e', 'l', 'l', 'o', '\0' }
).
Some old programs assumed that string constants are writeable; thus requiring GCC to support compiling those programs with the -fwriteable-strings
command line switch.