Eliminate "wild pointer"

Source: Internet
Author: User

The "wild pointer" is not a null pointer, but a pointer to the "junk" memory. Generally, null pointers are not incorrectly used, because if statements are easy to judge. However, the "wild Pointer" is very dangerous, and the IF statement does not work for it.

There are two main causes of "wild pointer:

(1) pointer variables are not initialized. When a pointer variable is created, it does not automatically become a null pointer. Its default value is random, which means it is random. Therefore, the pointer variable should be initialized at the same time when it is created, either set the pointer to null or set it to direct to the legal memory. For example

Char * P = NULL;

Char * STR = (char *) malloc (100 );

(2) After the pointer P is free or deleted, It is not set to null, which makes people mistakenly think P is a valid pointer.

Refer to free and delete what's wrong with pointers?

 

 

(3) pointer operations go beyond the scope of variables. This situation is hard to prevent. The example program is as follows:

Class
{
Public:
Void func (void) {cout <"func of Class A" <Endl ;}
};

Void test (void)
{
A * P;
{
A;
P = & A; // note the life cycle of
}
P-> func (); // P is a "wild pointer"
}

When the function test executes the statement p-> func (), object A has disappeared, and P points to a, so P becomes a "wild pointer ". But the strange thing is that I did not encounter any errors when running this program, which may be related to the compiler.

 



 



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.