The difference between free () function - new - delete operator and malloc ()

new - delete Operators of malloc() and free() difference functions

1. new- deleteOperator and malloc()- free()the difference function

  1. newAnd deleteoperators for substitution malloc()and free()functions.
  2. newCan really create an object, the malloc()function simply allocates memory.
  3. newAnd deleteoperators with more convenient (automates sizeofcomputational work, and automatically calls the appropriate constructor and destructor).
  4. newOperator 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.
  5. new- deleteis a C ++ keyword, it requires compiler support. malloc()- free()is a library function in the header file stdlib.hdeclaration.
  6. newWhen memory allocation fails, the default throws an abnormal program termination, it will not return NULL. If the operating system is unable to malloc()provide more memory, malloc()it returns a NULLpointer. For each slave malloc()pointer returns are checked to ensure that it is not NULLvery important.
  7. free()The argument must either be NULL, either from a previous malloc(), calloc()or realloc()the value returned. To free()pass a NULLparameter has no effect.
  8. malloc()A return type void *of pointer. It represents a standard void *type of pointer can be converted into any other type of pointer.
  9. 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 newoperator

newOperator 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 deleteoperator

Using the deleteoperator can release the front side with a newmemory 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 newoperator, is paired with deletethe operator, the effect is the release of previously newallocated 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 newand deleteoperator

Suppose a doublevariable space is needed. We can define a pointer doubletype pointer, and then run again when a request to allocate memory. This task can be used in the following statement newto 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 newthe operator returns to the idle memory to be allocated to doublethe memory address of a variable, a pointer and pvaluestores the address. Thereafter, using the preceding learned indirection operator, a pointer can pvaluebe referenced doublevariables.

*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 newoperator will throw an exception, so that the routine is terminated.

newVariables can also be created to initialize. Using the previous newallocation of doublevariables, 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 deleteoperator 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 pvaluedeposit 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 chartype 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 chararray of allocated space, and the address is stored pstrin. To delete an array just created, you must use the deleteoperator. 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 pstrmemory now contains the address may have been assigned to other uses of variables, of course, should not be used and therefore this pointer. When deleteafter 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 newoperators.

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 newoperator 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 autoautomatically 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 deleteto 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 newassigned 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 maxis a variable. Not the leftmost dimension specified variable, the compiler will generate an error message.

Published 525 original articles · won praise 1876 · Views 1.16 million +

Guess you like

Origin blog.csdn.net/chengyq116/article/details/105209316