C + + memory allocation

Source: Internet
Author: User

C + + memory management:

Variables and objects are allocated in memory by the compiler when compiling the program, but it also brings inconvenience, such that the array must be large and small, the pointer must point to an existing variable or object. Dynamic memory allocation solves this problem.

C + + defines 4 memory intervals: code area, global data area, stack area, heap area. Defining variables is the static storage allocation that is performed at the time of compiling the program, and all the dynamic allocations are basically done in the heap area. However, it is not so absolute that it is associated with both compilers and libraries. The parameters of the function are not necessarily allocated through the stack, which is related to the specific compiler. The return value for memory allocation failure is not necessarily null, and many compilers can catch exceptions thrown by the new operator.

Global Data Area Code Area Stack Area Heap Area
Data Code Stack Heap
Global variables Function Local variables New,delete Application Space
static data function parameters
Constant return address
Return data

the allocation and release of heap memory is the key to reusing limited resources.

* * pointer variable name = new type name (initial value);
Delete pointer name; * *

The new operator returns a pointer to the assigned type variable (object), while the dynamically created object itself does not have an identifier name. The new expression allocates an object from the heap, and then initializes the object with the value in parentheses. When an object is allocated from a heap, the new expression calls the library operator new (). For example:

int *pi = new int(0);

Note that when memory allocation fails, it usually returns a value of 0 (related to the library used), so the returned pointer is checked when memory is allocated dynamically.

When the delete operator is used, only the memory space pointed to by the pointer is freed, but the pointer itself is not undone and the memory space occupied by the pointer is not freed.

char *pc = new char;*pc = ‘a‘;int *pi = new int(8);
Stack Area Heap Area
Pc A
Pi 8

But after the function or program finishes executing the system stack, both the PC and PI variables will disappear, but the memory they point to is not automatically freed, then the memory will not be used unless the system restarts.

How to write protection:

char *pc = new char;*pc = ‘a‘;int *pi = new int(8);if (pc) {    delete pc;}if (pi) {    delete  pi;}char *string = new char[20];if (string == 0) {    return;}/* ... */delete []string;

The allocation of variables is not generated during compilation:
(1) Global variables and static variables are allocated at compile time in initialized or uninitialized data segments;
(2) Local variables are allocated from the stack during execution;
The member variables in the (3) class are assigned when the class is instantiated.


Expand your knowledge

1. sizeof operator

When it comes to C + + memory, let me think of the sizeof operator, which is slightly more detailed. sizeof is an operator in C/s + + that returns the number of bytes of memory that an object or type occupies, and the type of the return value is size_t (typedef).

Grammatical form:
(1) sizeof (object);
(2) sizeof (TYPE_NAME);
(3) sizeof object;

sizeof calculates an object by converting it to a type when calculating its size, and if it passes in expressions and functions, sizeof evaluates the size of the expression result type and function return type, and the function and expression itself are not called.

SizeOf's calculation occurs at compile time, so it can be used as a constant expression:

char array[sizeof(int) * 10];

For the basic data type of sizeof generally no problem, if the pointer needs to be noted, because the pointer is only the address of the Record object, that is, the width of the address bus inside the computer, the sizeof value of the array is equal to the number of bytes of memory in the array, it should be noted that when the array is a parameter, The array name is when the pointer is used.

char a1[] = "adb";int a2[3];sizeof(a1); //结果是4sizeof(a2); //结果是12

The sizeof about the struct is related to the data alignment problem of C + +, can go to see my previous article has detailed explanation.

2. Changes in memory management

Memory management has undergone several changes, but it has not been able to mature until now.

(1) from Malloc/free to New/delete. This change was the product of the rise of OOP technology at that time. Because C + + is a strongly typed language, the main outcome of new/delete is to strengthen the concept of type and reduce the need for forced type conversions. But for memory management, this change is not much of a breakthrough;

(2) from New/delete to Memory Configurator (allocator). Since STL is included in the C + + standard library, allocator is also introduced into C + + memory management, the entire STL component memory is allocated from the allocator, the STL itself is not recommended to use New/delete for memory management, Instead, we recommend the use of allocator. However, the introduction of allocator does not change the traditional C + + programmer concept, most people use the STL while still using new/delete in the cumbersome memory allocation/release process.

The main reasons are two. The first is that the STL designer is probably still out of memory management from the implementation of the container, so that STL users have a choice of memory management algorithms, the designer itself may not be aware of the importance of allocator. Second, the allocator itself is focused on the efficiency of attention, and does not focus on the C + + language users on the memory management concept of change.

C + + memory allocation

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.