C + + memory, new vs. malloc allocating memory differences?

Source: Internet
Author: User

One about memory
1, memory allocation method
There are three ways to allocate memory:
(1) Allocation from a static storage area. The memory is allocated at the time of program compilation, and the entire running period of the program exists in this block.
。 For example, global variables, static variables.
(2) Create on the stack. When executing a function, the storage unit of the local variable within the function can be created on the stack, and these are saved at the end of the function execution.
The storage unit is automatically released. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.
(3) Allocation from the heap, also known as dynamic memory allocation. The program uses malloc or new to request any amount of memory at run time, and the programmer
When you are responsible for freeing 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.
2. Memory Usage Error
A memory error is a very troublesome thing to happen. These errors are not automatically discovered by the compiler and are usually captured when the program is running.
And most of these errors are not obvious symptoms, and the hidden, increased the difficulty of error. Sometimes the user angrily to find you, the program is not
Any problems occur, you go, the wrong again attack. Common memory errors and their countermeasures are as follows:
* The memory allocation was unsuccessful, but it was used.
Novice programmers often make this mistake because they are unaware that the memory allocation will not succeed. A common workaround is to check before using memory
Whether the pointer is null. If you are using malloc or new to request memory, you should use if (p==null) or if (P!=null) for error-proof handling.
* The memory allocation succeeds, but it is not initialized to reference it.
There are two main causes of this error: one is the idea of no initialization, and the other is to mistakenly assume that the default initial value of the memory is all zero, leading to the reference value
Errors (such as arrays). There is no uniform standard for what the default initial value of memory is, although sometimes it is zero, and we would rather believe it.
Credible it has. So no matter how to create an array, do not forget to assign the initial value, even if it is assigned 0 values can not be omitted, do not bother.
* The memory allocation succeeds and has been initialized, but the operation crosses the memory boundary.

For example, the use of arrays often occurs when the subscript "more 1" or "less 1" operation. Especially in a for-loop statement, the number of cycles is easily
Error, causing array operations to be out of bounds.

* Forgot to release memory, causing memory leaks.

The function that contains this error loses one piece of memory each time it is called. At first, the system has plenty of memory and you can't see the error. There was a time.

The program suddenly dies, the system appears prompt: memory exhaustion.

Dynamic memory application and release must be paired, the program malloc and free use must be the same number, or there must be errors

(New/delete).

* Release the memory and continue to use it.
 
There are three types of cases:

(1) The object invocation in the program is too complex, it is difficult to find out whether an object has already freed the memory, this time should be re-

Design data structure, fundamentally solve the chaotic situation of object management.

(2) The return statement of the function is incorrectly written, note that you do not return a pointer to "stack memory" or "reference" because the memory is in the letter

is automatically destroyed at the end of the number body.

(3) After releasing memory with free or delete, the pointer is not set to null. Causes the "wild pointer" to be produced.

After rule 1 has requested memory with malloc or new, you should immediately check that the pointer value is NULL. Prevent use of memory with a pointer value of NULL

Rule 2 Do not forget to assign an initial value to both arrays and dynamic memory. Prevents memory that is not initialized from being used as the right value.

"Rule 3" avoids array or pointer subscript out of bounds, especially beware of "more 1" or "less 1" operations.

"Rule 4" the request and release of dynamic memory must be paired to prevent a memory leak.

"Rule 5" after releasing memory with free or delete, immediately set the pointer to NULL to prevent the "wild pointer" from being produced.

Two. Detailed New,malloc,globalalloc
1. New

Operators for dynamic allocation and revocation of memory by the new and delete operators

New usage:

1> opening a single variable address space

1) New int; Opens a storage space for the array, returning an address to that storage space. int *a = new

int is the assignment of an int-type address to an integer pointer a.

2) int *a = new int (5) acts as above, but assigns integers to 5 at the same time

2> Open Array Space

One-dimensional: int *a = new int[100]; Open an integer array space of size 100

General usage: new type [initial value]

Delete usage:

1> int *a = new int;

Delete A; Free space for a single int

2>int *a = new Int[5];

delete [] A; Free int array space

To access the structure space opened by new, it cannot be accessed directly from the variable name, but only through the assigned pointer.

Use new and delete to dynamically open and revoke the address space. If you run out of a variable (typically an array that is temporarily stored) when you are in a program,

The next time you need to use it, but you want to save the re-initialization effort, you can open up a space each time you start using it, and then undo it when you're done.

2. malloc
Prototype: extern void *malloc (unsigned int num_bytes);
Usage: #i nclude <malloc.h> or #i nclude <stdlib.h>
Function: Allocates a memory block of length num_bytes bytes
Note: If the assignment succeeds, it returns a pointer to the allocated memory, otherwise the null pointer is null.
Use the free () function to release memory blocks when memory is no longer in use.
The syntax for malloc is: pointer name = (data type *) malloc (length), (data type *) represents the pointer.
Description: malloc allocated memory space to the system to allocate a specified size byte. The return type is the void* type. void* indicates an indeterminate type

The pointer. c,c++ Specifies that the void* type can be cast to any other type of pointer.

Working mechanism of malloc () function
The real body of the malloc function now, it has a so-called idle list that connects the available memory blocks to a long listing. Call malloc

function, it looks for a block of memory along the join table that is large enough to satisfy the user's request. The memory block is then split in two (a large

Small is equal to the size of the user request, and the size of the other is the remaining bytes. Next, pass the memory allocated to the user to the user and

Return the remaining piece (if any) to the connection table. When the free function is called, it connects the memory blocks freed by the user to the idle chain. To

Finally, the idle chain is cut into a lot of small memory fragments, if the user requests a large memory fragment, then the idle chain may not be able to

A fragment that satisfies the user's requirements. The malloc function then requests a delay and begins to rummage through the memory fragments on the idle chain,

To organize and merge the adjacent small free blocks into larger chunks of memory.

Different from new
As you can see from the function declaration. malloc and new are at least two different: new returns a pointer of the specified type, and can automatically calculate the required

To size. Like what:
int *p;
p = new int; The return type is the int* type (integer pointer), and the allocation size is sizeof (int);
Or:
Int* Parr;
Parr = new int [100]; The return type is the int* type (integer pointer), and the allocation size is sizeof (int) * 100;
malloc, however, must be computed by us to calculate the number of bytes and forcibly converted to a pointer of the actual type after the return.
int* p;
p = (int *) malloc (sizeof (int));
First, the malloc function returns the void * type if you write: p = malloc (sizeof (int)); The program cannot be compiled,

Error: "Cannot assign void* to int * type variable". Therefore, the cast must be passed (int *).
Second, the argument to the function is sizeof (int), which indicates the size required for an integral type of data. If you write:
int* p = (int *) malloc (1);
Code can also be compiled, but in fact only allocates 1 bytes of memory space, when you put an integer inside, there will be 3 bytes without

Home can be returned, and directly "live in the neighbor's house"! The result is that the contents of the original data in the back memory are all emptied.

Three new malloc differences

1. malloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +. They can all be used to request dynamic memory and free memory.
2, new not only allocates memory, but also invokes the constructor of the class, so that delete invokes the class's destructor, and malloc allocates only memory, does not initialize class members, and free does not call destructors
3. Memory leaks can be checked out for malloc or new, except that new can indicate the row of that file, and malloc does not have that information.
4. Efficiency comparison of New and malloc
New can be thought of as the execution of malloc plus constructors.
The new pointer is directly with the type information.
And malloc returns all the void pointers

Reference http://www.cnblogs.com/fujinliang/archive/2012/10/12/2721624.html

C + + memory, new vs. malloc allocating memory differences?

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.