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
Yes, both
aandbare 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".