Re: Dereferencing a null-pointer allowed?
On May 8, 2:13 pm, Lutz Richter <l...@gmx.li> wrote:
given the following code:
-----------------------------
class B
{
public:
B(): Value(99) {}
int Get() { if (this) return Value; else return -1; }
private:
int Value;
};
int main()
{
B* b = 0;
cout << b->Get();}
-----------------------------
I wonder if this is allowed.
Definitly not. b->f() is the same as (*b).f(), and *b
dereferences a null pointer.
I did not have any problem with any
compiler yet. It works! But is this guaranteed?
Try uping the optimization. A good compiler will know that
"this" can never be null, and optimize out the test, always
executing the true branch. Throw in multiple inheritance or
virtual functions, and there's a good chance that the code will
core dump even without optimization.
Unfortunately Stroustrop & Co. do not mention this problem in their
books.
You mean that they don't say that you're not allowed to
dereference a null pointer? Or that they don't explain that
"p->" is the equivalent of "(*p)".
If anyone has a documentation about NOT doing the above example,
then please tell me.
According to the standard, "p->" is the equivalent of "(*p)",
"*p" is the dereferencing operator, and dereferencing a null
pointer is undefined behavior.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34