new
-
delete
Operators of
malloc()
and
free()
difference functions
new
-
delete
Operators of
malloc()
and
free()
difference functions
1. new
- delete
Operator and malloc()
- free()
the difference function
new
Anddelete
operators for substitutionmalloc()
andfree()
functions.new
Can really create an object, themalloc()
function simply allocates memory.new
Anddelete
operators with more convenient (automatessizeof
computational work, and automatically calls the appropriate constructor and destructor).new
Operator may allocate space for a new variable in a particular type of free memory. Alias free memory heap.malloc()
Dynamic memory allocation functions from the heap.new
-delete
is a C ++ keyword, it requires compiler support.malloc()
-free()
is a library function in the header filestdlib.h
declaration.new
When memory allocation fails, the default throws an abnormal program termination, it will not returnNULL
. If the operating system is unable tomalloc()
provide more memory,malloc()
it returns aNULL
pointer. For each slavemalloc()
pointer returns are checked to ensure that it is notNULL
very important.free()
The argument must either beNULL
, either from a previousmalloc()
,calloc()
orrealloc()
the value returned. Tofree()
pass aNULL
parameter has no effect.malloc()
A return typevoid *
of pointer. It represents a standardvoid *
type of pointer can be converted into any other type of pointer.- Boundary alignment requirements for the machine,
malloc()
returned to the starting position memory will always be able to meet the most demanding of boundary alignment type claims.
1.1 new
operator
new
Operator free memory dynamically allocated memory. After successfully allocated memory upon request, the operator returns a pointer pointing to a memory area provided by the head, if unable to allocate memory, so a default throws of abnormal program termination.
1.2 delete
operator
Using the delete
operator can release the front side with a new
memory of the assignment operator.
2. Dynamic Memory Allocation
During execution, often you need to program input data, to determine the amount of storage space should be given different types of variables allocated. Any program involving the processing of data items not known in advance, you can use this function allocates memory to store the data at runtime.
Because it is impossible to define any variables dynamically allocated at compile time, so they will not name the source. When creating these variables, the computer memory with the corresponding address to identify them, the address stored in the pointer. By means of power pointers and Visual C++
dynamic memory management tool that can quickly, easily make programs written with this flexibility.
2.1 heap alias - free memory
In most cases, when executing the program, the computer has an unused section of memory. These memory called stack, also sometimes referred to free memory. Using a special operator may allocate space for a new variable in a particular type of free memory. The operator returns the memory address assigned to the variable, it is the new
operator, is paired with delete
the operator, the effect is the release of previously new
allocated memory.
Can be assigned to certain variables in the program in the free memory space, these variables when no longer needed, the space allocated then released and returned to the free memory. In this way, this memory can be reused by other dynamically allocated variables. This technique is very powerful and can be very efficient use of memory.
Smart pointer is a pointer to the alternatives. Dynamic allocation of memory, particularly when the object to an array or a more complex dynamic allocation of memory, preferably using smart pointers. When no longer needed smart pointer, it will automatically release the memory, so we no longer need to worry about freeing memory.
2.2 new
and delete
operator
Suppose a double
variable space is needed. We can define a pointer double
type pointer, and then run again when a request to allocate memory. This task can be used in the following statement new
to complete the operator:
double *pvalue {};
pvalue = new double; // Request memory for a double variable
All pointers should be initialized. The use of dynamic memory usually involve a large number of free-floating pointer, thus ensuring that they do not contain false value is very important. If the pointer does not contain a valid address value, you should set it to nullptr
.
The second line in front of new
the operator returns to the idle memory to be allocated to double
the memory address of a variable, a pointer and pvalue
stores the address. Thereafter, using the preceding learned indirection operator, a pointer can pvalue
be referenced double
variables.
*pva1ue = 9999.0;
Our system may not allocate memory request, may be due to free memory in the memory already used up, the front or free memory because of using broken - that is not enough contiguous bytes need be provided to the variable space. However, we do not have to worry too much about that. If the system is unable to allocate memory, then the new
operator will throw an exception, so that the routine is terminated.
new
Variables can also be created to initialize. Using the previous new
allocation of double
variables, for example, whose address is stored in pvalue
, you can use the following statement at the same time create the variable will be initialized to 999.0
:
pvalue = new double {999.0}; // Allocate a double and initialize it
Of course, you can only create this pointer with a statement and initialized:
double *pvalue {new double{999.0}};
When a variable is no longer needed dynamically allocated, it may be delete
operator to release the memory occupied by it to the free memory:
delete pvalue; // Release memory pointed to by pvalue
Another variable that can be used this way will ensure that memory later. If you do not use delete
, and later in pvalue
deposit pointer to a different address value, you will not be able to release this memory, or use variables it contains, because we have lost the way to access the address. This condition is called memory leaks - especially appear in the user program in time.
Upon release pointer to memory, you should set the value of the pointer is nullptr
, otherwise, the suspension of the pointer will appear, we may pass this pointer to access freed memory.
2.3 is a dynamically allocated array
An array of dynamic memory allocation is very simple. Give the char
type of array allocation of space, you can write the following statement:
char *pstr {new char[20]}; // Allocate a string of twenty characters
The statement is 20 characters in the char
array of allocated space, and the address is stored pstr
in. To delete an array just created, you must use the delete
operator. The corresponding statement is as follows:
delete [] pstr; // De1ete array pointed to by pstr
Use square brackets to indicate you want to delete an array. When you delete an array from the free memory, it should always include the square brackets, otherwise the results will be unpredictable. Also note that, without specifying any number of dimensions, only need to write []
to.
Of course, the pointer pstr
memory now contains the address may have been assigned to other uses of variables, of course, should not be used and therefore this pointer. When delete
after some memory allocation before the operator to abandon further should always be reset to this pointernullptr
:
pstr = nullptr;
This ensures that we will not attempt to access memory had been deleted. Will no longer point to valid memory area pointer is reset to nullptr
.
You can initialize an array allocated memory space in an idle:
int *data {new int[10] {2,3,4}};
long *pprime {new long[4] {3L,6L,9L}};
The first statement creates an array of integers containing 10 elements, and the first three elements 2, 3 and 4 is initialized. The remaining elements are initialized to zero.
The second statement creates an array of long integer consists of four elements, and the first three elements initialized to 3L, 6L and 9L. The remaining elements are initialized to zero.
2.4 dynamically allocated multidimensional arrays
Compared with the one-dimensional array, as multi-dimensional array allocated free memory RAM is used to form slightly more complex new
operators.
Suppose already declared pointer pbeans
:
double (*pbeans)[4] {};
In order to make earlier in this chapter have used arrays beans[3][4]
to obtain space, you can use the following statement:
pbeans = new double [3][4] // Allocate memory for a 3x4 array
Only you need to specify an array dimension in square brackets after the array element type name. Of course, also be one step:
double (*pbeans)[4] {new double [3][4]};
As shown below, with the new
operator to assign an array of three-dimensional space just need to specify the third dimension:
auto pBigArray (new double [5][10][10]); // Allocate memory for a 5x10x10 array
This statement uses auto
automatically inferred pointer types. Do not forget, and can not be used in conjunction with the initialization list auto
. You can write the following statement:
auto pBigArray = new double[5][10][10]; // Allocate memory for a 5x10x10 array
No matter how many dimensions the array is created, you can use the following statement array destroyed and released into memory idle memory:
de1ete [] pBigArray; // Release memory for array
pBigArray = nullptr;
Always only need delete
to keep up with a pair of square brackets to the back of the operator, regardless of dimension associative array is.
You may be used to specify the most variable new
assigned one-dimensional array dimensions. Two-dimensional or multidimensional array The same is true, but only in designated leftmost dimension with that variable. All other dimensions must be a constant or a constant expression. So you can write:
pBigArray = new double[max][10][10];
Which max
is a variable. Not the leftmost dimension specified variable, the compiler will generate an error message.