tags:

views:

143

answers:

6

I wrote a little test to check for null pointer, I simplified it with int and 0, 1, instead of real classes, what I'm trying to test is something like this: return p ? 1 : 0; which in real world would be return p ? p->callmethod() : 0;

bool TestTrueFalse();
void main()
{
  int i = TestTrueFalse();

}

bool TestTrueFalse()
{  
    int one = 1;
    int * p =&one;    
    *p = 0;  

    return p ? 1 : 0;
}

now, you can see, that once the pointer becomes 0 again, the test fails, why? what's wrong with this? what's the solution?

+4  A: 
*p = 0;  

you probably meant

p = 0;

*p = 0 sets what the pointer points to, not the pointer

Anders K.
+1  A: 

When testing a pointer value with a conditional in C++, it will return true if the value is non-zero and false if the value is 0. In your sample p is slated to point at the local one and hence has a non-zero address (even though the value at the address is 0). Hence you get true

JaredPar
+1  A: 

A null pointer is a pointer which points to the address 0, not the value 0.

To set a pointer to null, do:

p = 0;

To elaborate, your code sets the pointed-to-int to 0. For example:

int i = 1;
int *p = &i;
assert(*p == 1); //p points to 1

*p = 0;
assert(*p == 0 && i == 0); //p points to the same location, but that location now contains 0
+1  A: 

The code *p = 0; does not set the pointer to null. It sets what p is pointing to zero.

Starkey
A: 

A pointer is an address in memory. int *p = &one; takes the address of the variable one, and stores it in p. *p = 0; stores 0 in the memory pointed to by p, meaning that the value of one is now 0. So, you have changed what p points to, but not p itself. TestTrueFalse() will return 1.

Dima
A: 

to test it for a null pointer before inspecting the value pointed to you might use code like

if(ip != NULL)

taken from http://www.eskimo.com/~scs/cclass/notes/sx10d.html

NULL might be safer in your code, as it is more compiler independent than just writing 0. and it might also be more clear for others to read in your code.

a1337q
this might also be useful here:http://stackoverflow.com/questions/551069/testing-pointers-for-validity-c-c
a1337q
NULL, in C++, is required to be 0. Any compiler that treats the two at all differently is not a C++ compiler. The advantage of NULL is that it signifies that it's supposed to be a pointer value, but the disadvantage is that it can be misleading. (I'm really looking forward to `nullptr` in the next C++ standard.)
David Thornley