可以/为什么使用char *的,而不是为const char *的返回类型造成死机? [英] Can/Why using char * instead of const char * in return type cause crashes?

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

问题描述

我读的地方,如果你想要一个C / C ++函数返回一个字符数组(而不是为std :: string),你必须返回为const char *而不是char *。否则后者可能会导致程序崩溃。

会有人能够解释这是否是真还是假?如果这是真的,为什么从函数返回一个char *如此危险?谢谢你。

 为const char * my_function()
{
    ....
}无效的主要(无效)
{
    焦X [] = my_function();
}


解决方案

如果你有一个返回字符串文字功能,那么它必须返回为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";
    }
}

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

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