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

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

编译会给出下面的提示:

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

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


因为test1,test2,test4他们都是直接返回指向内存的变量,编译的时候语法分析到就提出警告,test3,test6都是间接的指向内存,编译器没有深层的分析语法,所有,没有提出警告。


因为写编译器的人这么判断的.... 有时候可能你就是要返回一个指针本身呢。


编译器能做的是尽量给你警告,我觉得标准没有规定test_3、test_6这样的行为必须给警告。

【热门文章】
【热门文章】