In C, a string between quotes, "such as this", is called a string literal.
String literals, such as what you gave above, are not dynamically allocated. Typically, they're allocated at compile and/or link time, and may be allocated in read-only memory. (That is why, in C++, string literals are const char
as opposed to char
.)
Under the hood, some compilers stash "testing" in a string table, generating a special pointer to it. It's roughly equivalent to this:
char *const compiler_generated_pointer_to_testing = (char *) (compiler_generated_string_table + 12345);
...
const char compiler_generated_string_table[] = {
...
't', 'e', 's', 't', 'i', 'n', 'g', 0,
...
};
...
example( compiler_generated_pointer_to_testing );
That's one way it could play out. Many other implementations are legal. In any case, the implementation details are probably besides the point. The real main points to remember are:
- Compile-time string literals should be treated as
const
, even if the compiler doesn't require you to declare pointers to them as const char *
.
- They are allocated at compile and/or link time, not on the heap or the stack.
- Two instances of the same string (ie.
foo("testing")
and bar("testing")
in different parts of the program) are not guaranteed to be distinct pointers, nor are they guaranteed to be the same pointer value.
- You must never
free()
a string literal.
- You must never write to a string literal.
- A string literal will remain available through the life of a program, so it works fine as, say, a hash key.
Got all that? Any questions?