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 const char * (see comments below) static char[], but immutable. A string literal represents a pointer to statically allocated memory. Therefore:

  1. It is perfectly fine, to return a such a pointer.

  2. Your function return type must should be compatible with const char*, i.e., return type char * will give you at least a warning may give you trouble later on.

  3. If you function may return both a literal or malloced string you have to be very careful about memory management. freeing a string literal probably will segfault.