Analysis of dynamic memory allocation in C + +

Source: Internet
Author: User

Implementing dynamic memory allocation with the new operatorP = new T;T is any type name and P is a pointer of type T *. dynamically allocates a size of sizeof (T) bytes of memory space and assigns the start address of the memory space to P.  P = new T[n];T: Any type nameP: pointer of type T *N: The number of array elements to allocate, which can be an integer expressiondynamically allocates a size of sizeof (T) bytes of memory space and assigns the start address of the memory space to P.
int * pn;   2. int 5 ;   3 New int  - ];   4. pn[0;  
releasing dynamically allocated memory with the delete operator Use the " delete" operator to release the memory space that is dynamically allocated with "new"
int New int ;   2 5 ;   3. Delete p;
to release a dynamically allocated array with the delete operatordelete [] pointer;//The pointer must point to the array of new1. Heap Memory allocation:
C + + defines 4 memory intervals: The code area, the global variable and the static variable area, the local variable area, the stack area, the dynamic storage area, the heap (heap) area, or the free store.

Concept of the heap:
Typically, a variable (or object) is defined, and at compile time the compiler can know the size of the required memory space based on the type of the variable (or object), allowing the system to allocate a determined amount of storage space at the appropriate time. This memory allocation is called static storage allocation;
Some operands can be determined only when the program is running, so that they cannot reserve storage space for them at compile time, only when the program is running, the system allocates memory according to the requirements of the runtime, which is called dynamic storage allocation. All dynamic storage allocations are made in the heap area.
When a program runs to a variable or object that needs to be dynamically allocated, it must request to the system the storage space of the desired size of a block in the heap for storing the variable or object. When the variable or object is no longer used, that is, the end of its life, to explicitly release the storage space it occupies, so that the system can be re-allocated to the heap space, so that the use of limited resources reuse.

2. Allocation and release of heap memory
Heap space Request, release method:
In C + +, the application and release of the allocated storage space in the heap is done using the two operators of new and delete, respectively:
Pointer variable name =new type name (initialization);
Delete pointer name;
For example:
1, int *pi=new int (0);
It is roughly equivalent to the following code sequence:
2, int ival=0, *pi=&ival;

Difference: The variable that pi points to is allocated by the library operator new (), in the program's heap area, and the object is not named.

Heap space request, release instructions:
The ⑴.new operator returns a pointer to the assigned type variable (object). The variable or object that is created is indirectly manipulated by that pointer, and the dynamically created object itself has no name.
⑵. When defining variables and objects, name the object with an identifier, and dynamically call it a nameless object (note that the difference between the temporary objects in the stack is different: different lifetimes, different methods of operation, and temporary variables are transparent to programmers).
⑶. The heap area is not automatically initialized at allocation time (including clear 0), so it must be explicitly initialized with an initialization (initializer). The action sequence of the new expression is as follows: The object is allocated from the heap, and the object is initialized with the value in parentheses.

3. Heap space Request, release demo:
⑴. Explicitly initialized with an initialization (initializer)
int *pi=new int (0);
⑵. When the Pi life cycle ends, you must release the target that pi points to:
Delete pi;

Note that this frees up the memory space of the target referred to by PI, which is to revoke the target, called dynamic memory deallocation, but the pointer pi itself is not revoked, it still exists, and the memory space occupied by the pointer is not released.

Here is a description of the new operation
The ⑴.new operator returns a pointer to the assigned type variable (object). The variable or object that you create is indirectly manipulated by that pointer, and the dynamically created object itself has no name.
⑵. When defining variables and objects, name the object with an identifier, and dynamically call it a nameless object (note that the difference between the temporary objects in the stack is different: different lifetimes, different methods of operation, and temporary variables are transparent to programmers).
⑶. The heap area is not automatically initialized at allocation time (including clear 0), so it must be explicitly initialized with an initialization (initializer). The action sequence of the new expression is as follows: The object is allocated from the heap, and the object is initialized with the value in parentheses.

4. Creating a dynamic one-dimensional array in the heap
① Application Array Space:
Pointer variable name =new type name [subscript expression];
Note: "Subscript expression" is not a constant expression, that is, its value does not have to be determined at compile time and can be determined at run time.

② to release the array space:
Delete [] pointer variable name to the array;

Note: The square brackets are very important, if the DELETE statement is less square brackets, because the compiler considers the pointer to be the first element of the array, it will produce an incomplete recovery problem (only the space occupied by the first element is recycled), the square brackets are converted to an array of pointers, the entire array is recycled. Delete [] square brackets do not need to fill in the number of array elements, the system knows. Even if it is written, the compiler ignores it.
#include <iostream.h>2. #include <string.h>3.voidMain () {4.intN; 5.Char*pc; 6. cout<<"Please enter the number of elements in the dynamic array"<<Endl; 7. cin>>n;//N is determined at run time and can be entered in8. Pc=New Char[n];//Request memory space of 17 characters (8 characters and one terminator)9. strcpy (PC, "Dynamic allocation of heap memory");//  Ten. cout<<pc<<Endl;  One. delete []pc;//frees the N-character memory space that the PC points to A.return ;  -.}

5. Description of dynamic one-dimensional arrays
① variable n at compile time does not have the definite value, but in the run input, according to the runtime allocates the heap space, this is the dynamic allocation advantage, may overcome the array "big open small use" the disadvantage, in the table, the sorting and the lookup algorithm, if uses the dynamic array, the versatility is better. It is important to note that delete []pc] frees the N-character space, while the delete PC frees up only one character space;
② If you have a char *pc1, make pc1=p the same, you can also use delete [] pc1 to free the space. Although C + + does not check arrays for bounds, the amount of space allocated to an array is documented when the heap space is allocated.
The ③ does not have an initialization (initializer) and is not initialized with an array of arrays.

6. Pointer arrays and Arrays pointers
Pointer type:
(1) The type that the int*ptr;//pointer points to is int
(2) The type that the char*ptr;//pointer points to is Char
(3) The type that the int**ptr;//pointer points to is int* (i.e. an int * type pointer)
(4) int (*ptr) [the type that the 3];//pointer points to is an int () [3]//Two-D pointer declaration

Array of pointers:
An array is a pointer to the same type, which we usually call an array of pointers.
For example, int * a[2]; it's got 2 int * variables inside it.

int * a[2]; a[0newint[3];  a[1]=newint[3];  Delete a[0];  Delete a[1


Note that this is an array and cannot be delete [];

Array pointers:
A pointer to a one-dimensional or multidimensional array.
int * B=new INT[10]; Pointer to a one-dimensional array B;
Note that this time to release the space must be delete [], otherwise it will cause memory leaks, B becomes an empty cantilever pointer

int (*B2) [10]=new int[10][10]; Note that the B2 here points to the first address of a two-dimensional array of int.
Note: Here, B2 is equivalent to a two-dimensional array name, but does not indicate its bounds, that is, the number of elements of the highest dimension, but its minimum number of dimensions must be specified! Just like a pointer to a character, which is equivalent to a string, do not refer to a pointer to a character as a pointer to a string.
int (*B3) [30] [20]; A three-level pointer ――> A pointer to a three-dimensional array;
int (*B2) [20]; The second-level pointer;――> A pointer to a two-dimensional array;
b3=new int [1] [20] [30];
b2=new int [30] [20];
Delete these two dynamic arrays using the following formula:
delete [] B3; Delete (release) a three-dimensional array;
delete [] B2; Delete (release) a two-dimensional array;

Creating a dynamic multidimensional array in a heap
New type name [subscript expression 1] [subscript expression 2] ...;

Example: Creating a dynamic three-dimensional array
Float (*CP) [30][20]; Pointer to a 30-row, 20-column array, pointing to a two-dimensional array
cp=new float [15] [30] [20]; Set up an array of 15 30*20 arrays;

Note: The CP is equivalent to a three-dimensional array name, but does not indicate its bounds, that is, the number of elements of the highest dimension, just like a pointer to a character that is equivalent to a string, and do not refer to a pointer to a character as a pointer to a string. This is consistent with the nesting definition of the array.

Source: My previous blog: (has stopped updating) http://blog.csdn.net/p641290710/article/details/28302495

Analysis of dynamic memory allocation in C + +

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.