通过从本地C样式数组返回指针来获取悬空指针 [英] Getting a dangling pointer by returning a pointer from a local C-style array

查看:80
本文介绍了通过从本地C样式数组返回指针来获取悬空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码有些困惑:

I am a bit confused by the following code:

#include <iostream>

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

int main()
{
    auto x = f();
    std::cout << x;
}

我认为,此代码应为UB(未定义的行为).我们返回一个指向本地作用域内的C样式数组元素的指针.事情应该出错了.但是,我测试过的编译器都没有抱怨(我在g ++和clang上都使用了-Wall -Wextra -pedantic). valgrind也不抱怨.

In my opinion, this code should be UB (undefined behaviour). We return a pointer to a C-style array element inside a local scope. Things should go wrong. However, none of the compilers I tested with complain (I used -Wall -Wextra -pedantic on both g++ and clang). valgrind does not complain either.

上面的代码是否有效,或者像人们认为的那样是UB?

PS:运行它似乎会产生正确"的结果,即显示测试",但这并不表示正确.

PS: running it seems to produce the "correct" result, i.e. displaying "test", but that's not an indication of correctness.

推荐答案

不,它不是UB.

此:

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

可以重写为等效内容:

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


如果您做了类似 this 的事情:


If you did something like this:

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

现在那个是UB-我们将返回一个悬空指针.

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

这篇关于通过从本地C样式数组返回指针来获取悬空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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