且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可以/为什么使用char *的,而不是为const char *的返回类型造成死机?

更新时间:2023-09-29 08:44:10

如果你有一个返回字符串文字功能,那么它必须返回为const char *。这些不需要对由malloc堆将被分配,因为它们被编译成可执行文件本身的只读部分

例如:

 为const char * errstr(INT ERR)
{
    开关(ERR){
        案例1:返回error 1;
        案例2:返回error 2;
        案例3:回归错误3;
        案例255:回归错误255,使这个疏这样的人不要问我,为什么我没有用为const char *的数组;
        默认:回归未知错误;
    }
}

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:

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";
    }
}