Somebody told me this morning that the following is leagal.
The memory is automatically allocated. Is this correct?
It is correct that the storage for the literal will be allocated
by the compiler, without you needing you malloc() the string
or use something like
char X[12] = "It's a test";
But to clarify a way that your question could be read:
The memory that is allocated for the string literal in that code,
char *X = "It's a test";
will be "permanent" memory, in the sense that it will last for
the lifetime of the program, just as if you had used a "static"
object. The memory that will be used for the string literal
will *not* have "automatic storage" duration. So for example,
char *teststring(void) { char *X = "It's a test"; return X; }
This is allowed, and you can access the returned string after
the function returned. This constrasts with
char *teststring(void) { char X[12] = "It's a test"; return X; /* WRONG */ }
because the X in that routine would have automatic storage duration
and would become inaccessible once the routine returned.
Another important thing to watch out for is that when you do
use the string literal form,
char *X = "It's a test";
then the string pointed to is not necessarily writable; if you
were to command, for example, X[7] = 'T'; then the C standard
says the result is up to the implementation: the implementation
is allowed to store string literals in read-only memory.
Furthermore, if you had
char *teststring2(void) { char *Y = "a test"; return Y; }
then the implementation would be allowed to return Y as pointing
into the same memory as being used to hold "It's a test" .
So... *only* use that kind of assignment when you want "read-only"
access; if you need to write to the string, then use either
char X[12] = "It's a test"; OR
char X[] = "It's a test";
The second of these does the same as the first excepts saves you
from having to count the number of characters. (Remember to
include the hidden trailing 0 that every string has.)