Click here to Skip to main content
15,891,981 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How to recognize a wild pointer ?
Posted

The best thing is to prevent/avoid them in the first place.

As far as I know, there is no standard, implementation independant way to distinguish between an unitialized pointer and one that is pointing to allocated memory by examining the pointer value. As I understand it, examining the value of an uninitialized pointer in some environments could trigger a trap and halt your program.

The answer is not to have uninitialized pointers.

My recommendation is to use smart pointers and the RAII idiom. I personally tend to favor boost::scoped_ptr and shared_ptr (either from boost or std::tr1) depending on the situation.

If you insist on using raw pointers, whenever you define one, if you are not immediately setting it to some valid address, initialize it to NULL. Also immediately when you delete it, set it to NULL. Then it is either NULL or pointing to something. However, do recall that exceptions were added to C++ back in the 90's. To get your code correct with this approach accounting for the potential of exceptions could require creating a rat's nest of unmaintainable try-catch blocks. I'd suggest reconsidering adopting the smart pointer/RAII approach.
 
Share this answer
 
Local pointers that have not been initialised will contain random data so you cannot rely on the contents to determine whether they have been allocated. If this is something you care about then you should always initialise to NULL when you create them.
 
Share this answer
 
It will have a shaggy hair cut, and might try to bite you.

What on earth are you talking about ? Do you mean a pointer that has leaked memory ? By definition, that's one you have no handle to anymore.
 
Share this answer
 
In your example the pointer "p" is not allocated it point on a vars on the stack...

If a pointer is not initialize it can contain anything so you cannot ever be sure if the address is valid ...

Never assume a fix value for an unallocated var...
 
Share this answer
 
Sorry for my unclear question. I have a pointer and i want to know if it is allocated. For example

int a=1;
int* p; // some function like IsAllocated(p) return false
p=&a; // IsAllocated(p) return true

I found unallocated pointer return 0xfd in watch window but i don't know how to use it ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900