Here is an example code:
class IntWrapper
{
public:
IntWrapper(int value_ = 0): value(value_) {}
int getNumber()
{
return value;
}
void setNumber(int value_)
{
value = value_;
}
private:
int value;
};
class T
{
public:
T(){}
void test()
{
std::cout << ptr->getNumber() << std::endl;
ptr->setNumber(10);
std::cout << ptr->getNumber() << std::endl;
}
private:
IntWrapper *ptr;
};
int main( int argc, char* argv[] )
{
T t;
t.test(); // may cause segmentation fault
return 0;
}
ptr that's a dangling pointer. When I run that program it prints:
1
10
but it also may cause a segmentation fault (even if only a function which read a memory - getNumber is called).
Since ptr is never initialized it may point to anything - code, data, stack, unmapped memory, memory that is mapped but not in an in-use range. That is, the address in the ptr member variable could contain random leftover data, special values generated by the compiler or heap implementation, or ???
Reasoning about why you do or do not get a segmentation fault in these circumstances is not particularly useful or meaningful in most cases. Just don't do that. It's "undefined behavior" and can cause arbitrarily unpredictable things to happen.