Functions and return const char*

帅比萌擦擦* 提交于 2019-12-11 03:15:38

问题


const char* test(bool i)
{
    const char t[] = "aa\n";
    const char* p = "bbb\n";
    if(i)
        return p;
    return t;
}
int main(array<System::String ^> ^args)
{
     printf(test(true));
     printf(test(false));
     return 0;
}

That returns something of sort:

 bbb
 %^&$^$%

It is clear that test(false) returns a pointer to a local variable. The question is that p is also local variable. Why the memory for "bbb\n" is not cleaned after the function returns. I thought const char[] is interpreted same way as const char* but it is not true as it seems.


回答1:


p is a local variable, which you return by value, but points to a string literal, which resides in read-only memory, not in the automatic memory allocated for the method.

Returning t and the using it indeed results in undefined behavior.

Also, don't think of pointers and arrays to be equivalent.




回答2:


Although p is a local variable, what it points to is not local - it is a compile-time string constant; it is legal to return that constant's address from a function.

t is different, because the compile-time string constant is copied into an automatic storage area, causing an undefined behavior on dereferencing the returned pointer.



来源:https://stackoverflow.com/questions/10668923/functions-and-return-const-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!