Question: ```
#include <iostream>

class C
{
    private:
        int *o;
    public:
        C(int &i) { *o = i;}
        int* get_val() {return o;}
};

int main()
{
    int t = 9;
    C c(t);
    int* p = c.get_val();
    std::cout<<*p<<std::endl;
    int* h = c.get_val();           //seg fault
    std::cout<<*h<<std::endl;

    int f = 25;
    C g(f);
    int* q = g.get_val();           //seg fault
    std::cout<<*q<<std::endl;        

    return 0;
} 

```

There are two objects to the class C : 'c' and 'g'. 
Returning the private variable's pointer works fine for the first time, but, it results in seg fault, when called for the second time. Why is it so?

So, I commented out the second call and tried creating a new object and called tried to return the private variable's pointer. Even though, 'g' is another object of class C, returning it results in segmentation fault. Why is it so?

Answer: 
The constructor C::C(int) doesn't initialize the member variable o. It tries to write through the pointer o via \*o=i, but since o is uninitialized, the results are unpredictable.
You are not initialising C::o at all. The problem isn't that you're returning the private pointer; it's that you're assigning to memory you haven't allocated.

Here's the output from gdb with a breakpoint at line 8 (C's constructor):

```
Breakpoint 1 at 0x400960: file tmp.cc, line 8.

Breakpoint 1, C::C (this=0x7fffffffdd00, i=@0x7fffffffdd08: 9) at tmp.cc:8
8         C(int &i) { *o = i;}
$1 = (int *) 0x7fffffffddf0
9
9

Breakpoint 1, C::C (this=0x7fffffffdce0, i=@0x7fffffffdcec: 25) at tmp.cc:8
8         C(int &i) { *o = i;}
$2 = (int *) 0x0

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400969 in C::C (this=0x7fffffffdce0, i=@0x7fffffffdcec: 25) at tmp.cc:8
8         C(int &i) { *o = i;}

```

On my machine, the first call succeeded, but the second call causes the segfault, because g.o is 0x0.

You should initialise C::o before assigning to \*o, eg.

```
C(int &i) : o(new int) { *o = i;}

```