可能的重复:
返回本地或临时变量的地址
可以在其范围之外访问本地变量的内存吗?
假设我们有以下代码
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;
}
您已经编写了一个具有未定义行为的程序。UB并不意味着细分故障,这意味着可能发生任何事情。您运行了程序,发生了一些事情,只是您所期望的。故事的寓意是不要与UB一起编写程序,如果您这样做的事情很难理解。
您不应使用全局变量。在您的示例中,您所做的是未定义的行为。
如果您做过
之类的事情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
您应该非常重视这些警告。
当您定义函数中的变量时,它将在堆栈中分配,而当您从该变量的该函数驱动器返回时,将自动调用(如果类型具有任何destructor),但是与堆分配的对象,此时堆栈的内存将无法释放:
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;
}
但是,如果您的类型是具有驱动器的类,并且在使用之前需要建筑,那么您甚至可能会收到诸如细分故障之类的例外