My idea is to print the object it points to. I think a valid pointer should have a valid object. If we try to print out the object we verify if the pointer is valid. Am I right?
Asked
Active
Viewed 1,336 times
0
-
1Take a look at what Raymond Chen has to [say about this](http://blogs.msdn.com/b/oldnewthing/archive/2006/09/27/773741.aspx); even though he talks specifically about Windows, this should apply to most OSes in general. – Praetorian Nov 20 '13 at 16:43
-
possible duplicate of [C++ Is it possible to determine whether a pointer points to a valid object?](http://stackoverflow.com/questions/17202570/c-is-it-possible-to-determine-whether-a-pointer-points-to-a-valid-object) – Daniel Daranas Nov 20 '13 at 16:54
-
Many duplicates: [1](http://stackoverflow.com/q/6185821/96780), [2](http://stackoverflow.com/q/482315/96780), [3](http://stackoverflow.com/q/551069/96780), [4](http://stackoverflow.com/q/17202570/96780), [5](http://stackoverflow.com/q/4595675/96780), [6](http://stackoverflow.com/q/17202570/96780). – Daniel Daranas Nov 20 '13 at 16:58
1 Answers
1
I think a valid pointer should have a valid object.
Yes, that's the definition of a valid pointer.
If we try to print out the object we verify if the pointer is valid.
Unfortunately, you can't. You can check whether the pointer is null; but if it wasn't initialised properly, or if it pointed to an object that's been destroyed, it will be neither valid nor null.
If you want a pointer that's smart enough to know whether it's valid, you'll need a smart pointer.

Mike Seymour
- 249,747
- 28
- 448
- 644
-
How about if I try to print out what it's pointing. If it gives random address, it is not any more a valid pointer. That is what I thought. Is it right? – jsh6303 Nov 20 '13 at 16:51
-
@JiajuShen: I don't know what you mean. All addresses are "random", whether or not there's a valid object at that address. There's no reliable way to tell whether or not a pointer points to a valid object. You could perhaps detect *some* invalid pointers that don't represent an accessible address; but an invalid pointer could easily have an accessible address - either by chance, or because it used to point to a deleted object. – Mike Seymour Nov 20 '13 at 16:59