About the storage location and memory recovery mechanism of local variables and global variables in C + +

Source: Internet
Author: User

Local variables, parameter variables are stored in the stack, and when out of scope, the allocated memory is automatically reclaimed by the system outside the scope of the action.

New memory space is stored in the heap, is not managed by the scope, is not automatically reclaimed by the system, and frees up memory only when delete is used or the entire program ends.

Therefore, it is easy to forget the delete and cause a memory leak event. For example, in a function, you define:

A * a=new a ();

Pointer A will be destroyed after the function has finished running, but new memory will not be destroyed and delete a must be executed before it can be destroyed.

In addition to the static variable, the lifetime of the global variable is the entire program run time.

The smart pointer, in the case of a pointer being destroyed, destroys the memory pointed to by the pointer, preventing a memory leak from occurring.

This is a common case of memory leaks. Try to avoid manually managing pointers, using shared_ptr and unique_ptr in c++11 to manage them.

For more information, please refer to: 51965221

About the storage location and memory recovery mechanism of local variables and global variables in C + +

Related Article

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.