开发者社区> 问答> 正文

C++ 函数中返回局部指针地址的问题

我们都知道,C++ 函数中是可以进行局部变量的返回的,返回局部变量时要注意不能返回指向栈内存的指针!

这是因为局部变量的作用域是函数内部,函数一旦执行结束,栈上的局部变量会进行销毁,内存得到释放。因此,如果函数返回的是该局部变量的值拷贝,这是没有问题的。但是如果返回的是局部变量的地址,那么返回的只是该局部变量指针的拷贝,而随着函数运行结束,该拷贝指针所指向的栈内存已经被释放,那么指向一个未知区域就会导致调用的错误。

具体看下面的例子:

#include <iostream>
using namespace std;

int* test_1(){
    int d=2;
    int c = d;
    // return &d;
    return &c;
}

int* test_2(){
    int d[] = {1,2};
    return d;
}

int* test_3(){
    int d[] = {1,2};
    int *t = d;
    return t;
}

char* test_4()
{
    char str[]="HelloJacky";
    return str;
}

char* test_5()
{
    char* str=(char*)"HelloJacky";
    return str;
}

int* test_6(){
    int a = 1;
    int *b = &a;
    return b;
}

int main(void)
{
    int *p = 0;
    cout << *test_1() << endl;
    cout << *test_2() << endl;
    cout << *test_3() << endl;
    cout << *test_4() << endl;
    cout << *test_5() << endl;
    cout << *test_6() << endl;
}

编译会给出下面的提示:
screenshot
也就是说 test_1, test_2, test_4,编译器都会警告,引用栈空间的地址(一定要避免这种情况)。

那么问题来了,为什么 test_3,test_6 没有警告呢?

展开
收起
杨冬芳 2016-05-27 11:23:30 2847 0
1 条回答
写回答
取消 提交回答
  • IT从业

    我个人认为因为test1,test2,test4他们都是直接返回指向内存的变量,编译的时候语法分析到就提出警告,test3,test6都是间接的指向内存,编译器没有深层的分析语法,所有,没有提出警告。
    另外可以试试透过函数参数返回

    2019-07-17 19:17:29
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载