1

可能重复:
返回局部变量或临时变量的地址
局部变量的内存是否可以在其范围之外访问?

假设我们有以下代码

int *p;//global pointer
void foo() {
  int a=10;//created in stack
  p = &a;
}//after this a should be deallocated and p should be now a dangling pointer
int main() {
  foo();
  cout << *p << endl;
}

我想知道为什么会这样……应该是段错误!

好的未定义行为似乎合适..你能再次验证它吗?我试图在下面的代码中模拟上面的东西,但现在它给出了 SIGSEGV。

int main() {
    int *p=NULL;
    {
        int i=5;
        int *q = &i;
        p=q;
        delete q;//simulates the deallocation if not deallocated by the destructor..so p becomes a dangling pointer
    }
    cout << *p << endl;
}
4

3 回答 3

3

您编写了一个具有未定义行为的程序。UB 并不意味着段错误,它意味着任何事情都可能发生。你运行了你的程序,但发生了一些事情,这不是你所期望的。故事的寓意是不要用 UB 编写程序,如果你这样做,事情会变得非常难以理解。

于 2012-10-20T08:39:40.623 回答
1

你不应该使用全局变量。在您的示例中,您所做的是未定义的行为

如果你做了类似的事情

int* foo() {
  int a = 10; //created in stack
  return &a;
}

int main() {
  int *p = foo();
  cout << *p << endl;
}

您至少会收到警告:

prog.cpp:5: warning: address of local variable ‘a’ returned

您应该非常认真地对待这些警告。

于 2012-10-20T08:41:40.277 回答
-1

当您在函数中定义一个变量时,它将在堆栈上分配,并且当您从该函数返回时,该变量的析构函数将被自动调用(如果类型具有任何析构函数),但与堆分配的对象不同,堆栈的内存不会在这点:

void test1() {
    // assume on start of this function top of stack is 0x100
    int a = 10; // push 10 on to of stack and increase top of stack
                // Now top of stack is 0x100 + sizeof(int)
    a = 20;     // when you do this you are actually changing variable on stack
    p = &a;     // Get address of variable in stack!
                // So p is now 0x100
    // hidden return will restore top of stack to 0x100, pop return address, ...
}
int test2() {
    // again top of stack is 0x100
    int a2;     // a2 is in same address as a in previous function!
    a2 = 100;   // so this will overwrite value that pointed by p
                // because it point to same location
    return (int)&a2;
}

void main() {
    test1();
    test2();
    std::cout << *p << std::endl;
}

但是,如果您的类型是具有析构函数的类并且在使用前需要构造,那么您甚至可能会收到诸如分段错误之类的异常

于 2012-10-20T08:53:32.263 回答