returning a pointer to a literal (or constant) character array (string)?
That is actually OK. The string literal is usually allocated in an immutable memory area that remains available for as long as your program is running.
See also the answers to when does c/c++ allocate string literals.
It's ok in terms of allocation: the string literal is implicitly static
. It's not ok to return a non-const
pointer to a literal.
If you want to return a modifiable (non-const
) string, declare it a static char[]
. Or better, return a copy:
return strdup("something else");
Don't forget to free
afterwards. strdup
is non-ISO but available almost everywhere (except MSVC, I believe).
The type of a string literal is (see comments below) const char *
static char[]
, but immutable. A string literal represents a pointer to statically allocated memory. Therefore:
It is perfectly fine, to return a such a pointer.
Your function return type
mustshould be compatible withconst char*
, i.e., return typechar *
will give you at least a warningmay give you trouble later on.If you function may return both a literal or
malloc
ed string you have to be very careful about memory management.free
ing a string literal probably will segfault.