Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why size of pointed object of pointer is not zero even if we assigned pointer to NULL?

I am wondering why size of object pointed by pointer is not zero even if we assigned pointer to NULL.Can anyone explain this?

compiled on g++ 4.8,ubuntu 14.04

Foo * foo=NULL;
cout<<"Size of pointed object of foo:"<<sizeof(*foo)<<endl;  //why it is not zero
like image 243
Ram Charan Avatar asked Oct 30 '25 20:10

Ram Charan


2 Answers

sizeof is a compile time directive. Thus, there is no run time check to see if the pointer actually points to a real object. There is no check of the pointer at all. the directive is replaced by the compiler by the size in bytes of the type, Foo in your case.

like image 123
nivpeled Avatar answered Nov 01 '25 10:11

nivpeled


Inside sizeof we are in an unevaluated context. Any expressions inside it will never be evaluated. sizeof only cares about the type of the expression you pass it, and the type of *foo is of course Foo&. sizeof ignores the reference, so it returns the size in bytes that an object of type Foo would occupy.

Note again that the expression you wrote is never evaluated, so it does not matter whether a Foo object exists where foo points to - the value of foo (and the contents of the memory it points to) are of no relevance to sizeof.

like image 27
Max Langhof Avatar answered Nov 01 '25 12:11

Max Langhof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!