范围之后的交易结束
deallocation after scope has ended
可能的重复:
返回本地或临时变量的地址
可以在其范围之外访问本地变量的内存吗?
假设我们有以下代码
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;
}
但是,如果您的类型是具有驱动器的类,并且在使用之前需要建筑,那么您甚至可能会收到诸如细分故障之类的例外
相关文章:
- 为什么在这个代码结束循环中没有得到结束
- 试图对缓存进行跨步测试,但程序并没有结束
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么擦除方法会影响结束方法
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 删除映射和分割错误中的一个过去结束元素
- 如何使用 SFML 在贪吃蛇游戏中定义游戏结束?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- 在函数结束后使用指向变量的指针是否安全?
- C ++尝试并捕获未结束的程序
- 为什么我的程序在输入某个形状的面积的测量值后没有结束?
- 取消引用结束指针到数组类型的一个
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 结束另一个线程中使用的对象的生存期
- 全局向量导致 C++ 程序结束时出现段错误
- 程序显示以退出代码 0; 结束
- 如何显示函数开始、结束行和函数体?
- C++ 从具有开始位置和结束位置的列表中删除
- 范围之后的交易结束
- 尝试在选择交易后阻止银行程序结束.C++