Getting a dangling pointer by returning a pointer from a local C-style array

后端 未结 2 1172
青春惊慌失措
青春惊慌失措 2021-02-02 05:43

I am a bit confused by the following code:

#include 

const char* f()
{
    const char* arr[]={\"test\"};
    return arr[0];
}

int main()
{
             


        
2条回答
  •  生来不讨喜
    2021-02-02 06:24

    The array arr has local storage duration and will disappear at the end of scope. The string literal "test" however is a pointer to a static storage location. Temporarily storing this pointer in the local array arr before returning it doesn't change that. It will always be a static storage location.

    Note that if the function were to return a C++ style string type instead of a C style const char *, the additional conversion/bookkeeping would likely leave you with a value limited in lifetime according to C++ temporary rules.

提交回复
热议问题