I read somewhere that if you want a C/C++ function to return a character array (as opposed to std::string), you must return const char* rather than char*. Doing the latter may cause the program to crash.
Would anybody be able to explain whether this is true or not? If it is true, why is returning a char* from a function so dangerous? Thank you.
const char * my_function()
{
....
}
void main(void)
{
char x[] = my_function();
}
If you have a function that returns “string literals” then it must return const char*. These do not need to be allocated on the heap by malloc because they are compiled into a read-only section of the executable itself.
Example: