开发者

testing for valid pointer in c++

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 : 开发者_如何学Go0;
}

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


*p = 0;  

you probably meant

p = 0;

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


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


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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜