-2
class B
{
public:
    B():a(0), b(0) { }
    B(int x):a(x), b(0) { }
private:
    int a;
    int b;
};

class A
{
public:
    A(B* ptr):pB(ptr) { }
    void modifypB() 
    { 
        delete pB; 
        pB = NULL; 
    }
    void printBSize() 
    { 
        if( pB != NULL )
            cout<<"pB pointing to Obj size:"<<sizeof(*pB)<<endl; 
        else
            cout<<"pB pointing to Obj size:"<<sizeof(*pB)<<endl; 
    }

private:
    B *pB;
};


void main()
{
    B *bObj = new B(10);
    cout<<"Size of bObj:"<<sizeof(*bObj)<<endl;

    A aObj(bObj);
    cout<<"Size of aObj:"<<sizeof(aObj)<<endl;

    cout<<"Before De-allocating: ";
    aObj.printBSize();
    aObj.modifypB();
    cout<<"After De-allocating: ";
    aObj.printBSize();
}

Output:

Size of bObj: 8
Size of aObj: 4
Before De-allocating: pB pointing to Obj size: 8
After De-allocating: pB pointing to Obj size: 8

Why the size of *pB is 8, even after de-allocation ?

Kara
  • 6,115
  • 16
  • 50
  • 57
  • 1
    Just because you `delete` the pointer and set the value of the pointer equal to `NULL` doesn't mean the memory it's pointing to has been changed at all. You just have undefined behavior. – dwcanillas May 11 '15 at 14:53
  • Its just like when you delete a file. deleting the file does nothing but remove the listing of that file from the file table. It is still there on the harddrive until you overwrite it. – NathanOliver May 11 '15 at 14:56
  • What did you expect instead? – Lightness Races in Orbit May 11 '15 at 15:07
  • @dwcanillas: It's not even UB. `sizeof` uses the static type of the expression, without evaluating it; so it's defined to be `sizeof(B)` whatever the pointer's value. – Mike Seymour May 11 '15 at 15:12
  • @MikeSeymour yeah, I didnt read his question close enough, but I chose to leave my comment anyway. My comment is related to the question he was asking, but not to the behavior in his example. – dwcanillas May 11 '15 at 15:12

2 Answers2

4

Why the size of *pB is 8, even after de-allocation ?

sizeof(*pB) is evaluated at compile time based on the type of *pB. Its value does not depend on the value of pB at run time.

You are printing sizeof(B) in both branches of your if statement, which is 8 on your platform.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
3

sizeof(*p) gives you the size of the object which the compiler has determined at compile-time and not at runtime.

Try this:

int main(void)
{
     std::string *string_pointer = 0;
     std::cout  << sizeof(*string_pointer) << std::endl;
     return 0;
}

This will not segfault but print the size of the std::string-class.

Patrick B.
  • 11,773
  • 8
  • 58
  • 101