A wild pointer, also known as a stray pointer, is a pointer to "junk" memory. The memory that the pointer points to has been reclaimed by the operating system and the program is no longer accessible.
The wild pointer, instead of a null pointer, appears to be pointing to legitimate memory, but the memory is actually freed.
Here are a few ways to prevent wild pointers.
1) When declaring pointers, remember to initialize, for example:
char* P=null;
2) When the pointer has no use value, remember to release, after the successful release, remember to assign NULL to the pointer. For example:
if (NULL! = p) { delete P; p = NULL;}
3) If the pointer is an input parameter to a function, the pointer is first checked before referencing the parameter.
Use ASSERT (null! = p) At the entrance of the function to validate the parameter, or use if (null! = p) to test. It will remind the pointer not to initialize, to play the function of locating error. The assert is a macro, and if the conditions in the parentheses are not met, the program terminates and prompts for an error. When you are finished using the pointer, be sure to release the memory that the pointer points to.
4) Use reference substitution pointers whenever possible.
Refers to the ability to have pointers, and it also has the function of ordinary variables. The reference to the corresponding variable must be real. A reference to an input parameter as a function has a more direct visual effect than a pointer. For example, a pointer implementation of the SWAP function and a reference implementation.
The pointer implements a two-number interchange void swap (int *pa,int *pb) { int tmp=0; TMP=*PA; *PA=*PB; *pb=tmp;} The reference implements a two-number interchange void swap (int &pa,int &pb) { int tmp=0; TMP=PA; PA=PB; Pb=tmp;}
Comparing the implementation of the above two swap functions, it can be seen that: by reference to achieve numerical interchange, when the function calls, only need to pass two integers to the swap function.
By using pointers for numeric exchange, the addresses of the two integers must be passed to the swap function when the function is called. In addition, if the passed pointer is a wild pointer, the result is disastrous.
5) Use smart pointers to avoid wild pointers.
Smart pointers can effectively avoid wild pointers if different objects require access to the same pointer on the heap. With smart pointers (recommended shared_ptr) for packaging, different objects can have a smart pointer wrapped pointer, each access before the use of a smart pointer method _expired the validity of the pointer check, if the failure, it indicates that the object has been released.
Several methods of preventing wild pointers