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

后端 未结 2 1174
青春惊慌失措
青春惊慌失措 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:30

    No, it's not UB.

    This:

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

    Can be rewritten to the equivalent:

    const char* f()
    {
        const char* arr0 = "test";
        return arr0;
    }
    

    So we're just returning a local pointer, to a string literal. String literals have static storage duration, nothing dangles. The function really is the same as:

    const char* f()
    {
        return "test";
    }
    

    If you did something like this:

    const char* f() {
        const char arr[] = "test"; // local array of char, not array of char const*
        return arr;
    }
    

    Now that is UB - we're returning a dangling pointer.

提交回复
热议问题