Three ways to allocate memory in C + +

Source: Internet
Author: User

from the static storage area allocation : There is a program compiled at the time of the allocation, this block exists in the entire running period of the Program. For example, global variables, static Variables. The lifetime of a statically allocated zone is the entire software runtime, which means that the software runs from the beginning to the end of the software Termination. This memory will only be reclaimed by the system after the software has been terminated.

Create on Stack : When executing a function, the storage unit of the local variable within the function can be created on the stack, which is automatically freed when the function is Executed. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory Capacity. The lifetime of the space allocated in the stack is related to the function and class in which the variable Resides. If it is a local variable defined in the function, then its lifetime is when the function is called, and if the function ends, the memory will be Reclaimed. If it is a member variable in a class, its lifetime is the same as the lifetime of the class Instance.

allocation from the heap : Also known as dynamic memory Allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or Delete. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the Most. The memory allocated on the heap, the lifetime is from the call to new or malloc, to call delete or free to End. If you do not drop the delete or Free. The space must be recovered by the software before it is Finished.

Three ways to allocate memory 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.