可以/为什么在返回类型中使用 char * 而不是 const char * 会导致崩溃? [英] Can/Why using char * instead of const char * in return type cause crashes?

查看:17
本文介绍了可以/为什么在返回类型中使用 char * 而不是 const char * 会导致崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读到,如果您希望 C/C++ 函数返回字符数组(而不是 std::string),则必须返回 const char* 而不是 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.

谁能解释这是否属实?如果是真的,为什么从函数返回 char* 如此危险?谢谢.

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();
}

推荐答案

如果你有一个返回字符串文字"的函数,那么它必须返回 const char*.这些不需要通过 malloc 在堆上分配,因为它们被编译成可执行文件本身的只读部分.

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.

例子:

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

这篇关于可以/为什么在返回类型中使用 char * 而不是 const char * 会导致崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆