C++ 函数中返回局部指针地址的问题
PHP中文网
PHP中文网 2017-04-17 13:45:52
0
3
561

我们都知道,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 没有警告呢?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
Peter_Zhu

Because test1, test2, and test4 all directly return variables pointing to memory, a warning will be issued when the syntax is analyzed during compilation. Test3, test6 all point to memory indirectly, and the compiler does not have deep analysis syntax. So, there is no Give a warning.

黄舟

Because the people who wrote the compiler judged it this way... Sometimes you may just need to return a pointer itself.

小葫芦

What the compiler can do is try to give you warnings. I think the standard does not stipulate that behaviors like test_3 and test_6 must give you warnings.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template