I understand the concept of dangling pointers, func2 returns address of deallocated memory. In func1 instead of returning the address we store by passing a double pointer. Isn't this also a case of dangling pointer ?
#include <iostream>
void func1(int **x){
int z = 10;
*x = &z;
}
int *func2(){
int z=11;
return &z;
}
int main() {
int *a;
func1(&a);
std::cout << *a << std::endl;
int *b = func2();
std::cout << *b << std::endl;
return 0;
}
OUTPUT: 10 seg fault
CodePudding user response:
In both cases, you are dereferencing a dangling pointer, which invokes undefined behavior.
This means that you cannot rely on any specific behavior. You may get a segmentation fault or your program may work as intended, or something else might happen. The behavior may be different on different compilers. Even on the same compiler the behavior may be different, depending on the compiler settings, such as the optimization level. Also, simply updating your compiler to a new version may cause the behavior to change.
Asking why you are not getting a segmentation fault when you are invoking undefined behavior is not a meaningful question. It is like driving your car through an intersection when you have a red light and then asking why you did not collide with another car. If you break the rules, you cannot rely on anything specific to happen.
You may want to read this similar question:
Can a local variable's memory be accessed outside its scope?
CodePudding user response:
Yes, both a
and b
are dangling pointers when you dereference them and either dereference therefore makes the program invalid.
But dereferencing a dangling pointer causes undefined behavior. That means that there is no guarantee for any particular behavior whatsoever. There is no guarantee for a segfault. There is no guarantee for a particular output. There is no guarantee that it won't look as if accessing the dangling pointer to the out-of-lifetime variable "worked".