Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can/Why using char * instead of const char * in return type cause crashes?

Tags:

c

char

constants

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();
}
like image 776
Andy Avatar asked Sep 14 '09 13:09

Andy


1 Answers

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:

const char* errstr(int err)
{
    switch(err) {
        case 1: return "error 1";
        case 2: return "error 2";
        case 3: return "error 3";
        case 255: return "error 255 to make this sparse so people don't ask me why I didn't use an array of const char*";
        default: return "unknown error";
    }
}
like image 83
Zan Lynx Avatar answered Oct 14 '22 01:10

Zan Lynx