C ++ delete a pointer using delete (1)

Source: Internet
Author: User

As we all know, when we use new to create a pointer, We must delete the pointer using delete after we use it. However, it is worth noting that it is just as simple as deleting this pointer? Next, we will use a program to illustrate this problem:


# Include
02
Using namespace std;
03
Int main ()
04
{
05
Int * p = new int;
06
* P = 3;
07
Cout <"value read by the pointer p after 3 is assigned to the p address:" <* p <endl;
08
Delete p;
09
Cout <"value read by pointer p after space deletion:" <* p <endl;
10
Long * p1 = new long;
11
* P1 = 100;
12
Cout <"address saved in Pointer p after creating a new space:" <p <endl;
13
Cout <"pointer to the new space p1 saved address:" <p1 <endl;
14
* P = 23;
15
Cout <"value read by the pointer p after 23 is assigned to the p address:" <* p <endl;
16
Cout <"the value read by the pointer p1 after 23 is assigned to the address p:" <* p1 <endl;
17
Delete p1;
18
Return 0;
19
}
In the above program, we will delete the pointer p using delete in row 8th. However, let's look at the output results of the program:

 

Compare the above program to analyze the output. First, we initialize a pointer p in row 5th of the program. Then output the value read by the pointer p. The program will certainly output 3 because of the 6th rows. Then, we deleted the pointer p in row 8th of the program. However, we are surprised to find that the value read by the pointer p can be output in the second row of the program. Didn't we delete it? Actually, debug ,:


 

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.