Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Dereferencing a null pointer

Hello,
Can someone please give an example and explain the concept of dereferencing a null pointer and why it's such a bad idea and what we need to do to make sure we don't end up in this situation ?
Thanks.
[234 byte] By [ami] at [2007-11-11 9:59:03]
# 1 Re: Dereferencing a null pointer
Hi,
examlpe:

char* pChar = 0;
char c = *pChar; // de-reference 0-pointer: just try what happens and you
// know why it's a bad idea! ;-)

basically pChar points to memory address 0, which does not belong to your process.
So trying to access the contents (which is what the de-ref ultimately does) causes
an exception.

Cheers,

D
drkybelk at 2007-11-11 20:59:42 >
# 2 Re: Dereferencing a null pointer
null pointers are easy, you can check each pointer against null. The error that is worse is to dereference a garbage pointer which has "random" values in it:

char *cp;
sprintf(cp, "bad idea"); //very hard to find error unless you get lucky and it crashes. If it compiles and runs, you might have no error, might change the value of a different variable, or a million other bad things.

to fix it, you would want to always initialize pointers to null.
so
char *cp = null; // safe!
jonnin at 2007-11-11 21:00:36 >
# 3 Re: Dereferencing a null pointer
C and C++ guarantee that no objects shall be stored in the memory address 0. This means that a pointer that has this value must be a pointer that isn't bound to any object. Dereferencing a pointer means accessing the object bound to the said pointer. Since no object is abound to a null pointer, dereferncing it means accessing a non-existent object, which is like jumping into an empty pool.
Danny at 2007-11-11 21:01:41 >