Memory reuse when using heap memory in C/C ++

Source: Internet
Author: User

In a C/C ++ program, if the heap memory management mechanism is used, how is the memory allocated and recycled?

First look at a program:

 

# Include <iostream> using namespace std; int main (void) {int * x = new int; int * y = new int; * x = 1; * y = 2; cout <"* x =" <* x <endl; cout <"x =" <x <endl; delete x; int * z = new int; * z = 3; cout <"* z =" <* z <endl; cout <"z =" <z <endl; * x = 5; cout <"* z =" <* z <endl; return 0 ;}

This is because the program uses the heap memory management mechanism and there is a problem of memory reuse. The whole process is: when the program releases the memory of x, and then allocates the memory of z, this is the problem, because z occupies the memory of x, this means that the address of x and z is the same now !!! This is a terrible bug, because a pointer x, which is supposed to be invalid, can now change the content pointed to by the valid pointer z !! What should we do? In fact, we can clear the pointer every time we release the heap memory space pointed to by a pointer, that is, we need to add this code after delete:

X = NULL; or x = 0;

Although clearing a pointer may cause a program to crash, we would rather crash the program than make it extremely difficult to debug, because when the program crashes, we can observe to find the problem, however, it is difficult to find out the problem of a program like above !!!

 

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.