函数中指向局部变量的全局指针

时间:2014-05-27 12:39:05

标签: c++ pointers

#include <iostream>
using namespace std;

int *ptr;

void func1() {
    int a = 10;
    ptr = &a;
}

int main()
{
    func1()
    cout << *ptr << endl;
    return 0;
}

./ a.out正确地给出了10。

在上面的代码中,&#39; a&#39;是局部变量,其范围将在func1()内。根据我的理解,当激活方法时,分配一块称为激活记录的存储单元,它包含当前方法调用的所有局部变量和形式参数。激活记录在方法执行期间使用,然后在执行结束时被删除。删除激活记录后,将破坏局部变量和形式参数的内存位置,并且它们包含的值将丢失。但是在这里,在打印存储在&#39; a&#39;的存储器地址中的值时的主要功能。正确地给出10。 Pl澄清。

3 个答案:

答案 0 :(得分:3)

简短回答:这是未定义的行为。

&a的值仅在函数func1内有效,在main中访问它是未定义的行为,其值保持“有效”可能因为它仍然在堆栈,但你不应该依赖未定义的行为。

答案 1 :(得分:1)

&amp; a处的10的值保留在内存中,因为没有任何内容会覆盖它。如果你打电话给另一个函数,你可能不会再得到10。

答案 2 :(得分:0)

这是非常危险的。当超出范围时,本地对象/变量会自动释放(释放),因此局部变量的指针在范围之外是未定义的。

void func1() {
    int a = 10; // local variable, goes out of scope on return from this function
    ptr = &a; // pointer of local variable is RISKY to pass, as this will be gone
}

如果您需要内部变量的值,请按以下值传递此值,例如

int func1() {
    int a = 10; // local variable, goes out of scope on return from this function
    return a; // fine, as local variable will be copied to a temporary before return
}