The difference between malloc and new

Source: Internet
Author: User

1. malloc () function
The full name of 1.1 malloc is the memory allocation, which is called dynamic RAM allocation in Chinese.
Prototype: extern void *malloc (unsigned int num_bytes);
Description: Allocates a block of memory with a length of num_bytes bytes. If the assignment succeeds, returns a pointer to the allocated memory, and the allocation fails to return a null pointer null. Use the free () function to release memory blocks when memory is no longer in use.

1.2 void *malloc (int size);
Description: malloc has requested the system to allocate a memory space that specifies size bytes, and the return type is the void* type. Void* represents a pointer to an indeterminate type. c,c++ Specifies that the void* type can be cast to any other type of pointer.
Note: void* represents an undefined type of pointer, more specifically, when requesting memory space, it is not known if the user is using this space to store what type of data (such as char or int or ...). )

1.3 Free
void *firstbyte: This function returns the space previously allocated by malloc back to the program or the operating system, which frees up the memory and lets it regain its freedom.

1.4 Precautions
1) After you have applied for memory space, you must check whether the assignment was successful .
2) When you do not need to use the requested memory, remember to release, after the release should be pointed to the memory pointer to null, prevent the program accidentally used it.
3) The two functions should be paired. If it is not released after the application is a memory leak, if it is released for no reason, nothing is done. release can only once, if released two times and more than two times an error (releasing null pointer exception, releasing the null pointer is actually equal to nothing, so release the null pointer released how many times no problem).
4) Although the type of the malloc () function is (void *), any type of pointer can be converted to (void *), but it is better to make a forced type conversion before, as this will avoid some compiler checks.

Where did 1.5 malloc () Get the memory space?
is to get space from inside the heap. That is, the pointer returned by the function is a piece of memory pointing to the heap. The operating system has a linked list that records the free memory address. When the operating system receives a request for a program, it iterates through the list and then finds the heap node where the first space is larger than the requested space, and then deletes the node from the list of idle nodes and assigns the space of that node to the program.

2. New operator

2.1 C + +, use new and delete to dynamically create and release arrays or individual objects .

When you create an object dynamically, you only need to specify its data type, rather than naming the object , and the new expression returns a pointer to the newly created object , which we can access through a pointer .
int *pi=new int;
This new expression creates an integer object in the heap area, returns the address of the object, and initializes the pointer pi with that address.

2.2 Initialization of dynamically created objects

Dynamically created objects can be initialized in the same way as initialization variables.
int *pi=new int (100); The object that the pointer pi points to is initialized to 100
String *ps=new string (9 ');//*ps is "9999999999"

If no display initialization is provided, the default constructor for the class is initialized for the class type, and the object of the built-in type is not initialized .
You can also initialize values for dynamically created objects:
int *pi=new int ();//initialized to 0
int *pi=new int;//pi points to an int that is not initialized
String *ps=new string ();//initialized to an empty string (for class types that provide a default constructor, it is not necessary to initialize their objects for value)

2.3 Undoing dynamically created objects

The Delete expression releases the address space that the pointer points to.
Delete pi;//Release a single object
Delete []pi;//release array
It is illegal to use delete if the pointer is pointing to a memory address that is not new allocated.

2.4 After the delete, reset the value of the pointer

Delete p; After executing the statement, p becomes an indeterminate pointer, and on many machines, although the P value is not explicitly defined, it still holds the address of the object it was previously referred to, and the memory that P points to is already freed, so p is no longer valid. At this point, the pointer becomes a dangling pointer (the dangling pointer points to the memory where the object was stored, but the object no longer exists). Dangling pointers often cause program errors and are difficult to detect.
Once you have deleted the object that the pointer refers to, set the pointer to 0 immediatelyso that it is clear that the pointer is no longer pointing to any object. (0 value pointer: int *ip=0;)

2.5 Distinguishing between 0 value pointers and null pointers

A 0-value pointer, which is a pointer to a value of 0, can be any type of pointer, can be a generic variant type void* can also be a char*,int*, and so on.
Null pointer, in fact, the null pointer is just a programming concept, such as a container may have empty and non-empty two basic state, and in non-empty may store a value is 0, so the null pointer is a human-held pointer does not provide any address message. : http://www.cnblogs.com/fly1988happy/archive/2012/04/16/2452021.html

What is returned when the 2.6 new allocation fails?

1993 ago, C + + always required operator new to return 0When memory allocation failed, and now requires operator new to throw a Std::bad_alloc exception . Many C + + programs are written before the compiler starts to support the new specification. The C + + Standards Committee does not want to abandon the existing code that follows the return 0 specification, so they provide a different form of operator new (and operator new[]) to continue providing the return 0 feature. These forms are called "no throws" because they have not used a throw, but instead use the Nothrow object with the entry point of new :
Class Widget {...};

Widget *pw1 = new widget;//assignment failed to throw Std::bad_alloc

if (PW1 = = 0) ...//this check must fail.

Widget *pw2 = new (nothrow) widget; Returns 0 if allocation fails

if (pw2 = = 0) ...//This check may be successful

3. The difference between malloc and new

3.1 New Returns a pointer of the specified type and can automatically calculate the desired size.
Like what:
1) 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;
2) While malloc must be counted by us and forcibly converted to a pointer of the actual type after the return.   
int* p;
p = (int *) malloc (sizeof (int) *128);//Allocate 128 (can replace the value according to actual needs) integer storage unit and store the first address of these 128 contiguous integer storage units in the pointer variable p
Double *pd= (double *) malloc (sizeof (double) *12);//allocate 12 double type storage units and store the first address in the pointer variable PD

3.2 malloc allocates memory and cannot initialize the resulting memory , so the value of a new piece of memory will be random .
In addition to the method of allocation and final release, pointers are obtained through malloc or new and are consistent on other operations.

4. Why New/delete with Malloc/free?

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) for objects of non-intrinsic data types , the light Maloc/free cannot satisfy the requirements of dynamic objects. objects are automatically executed when they are created, and the object executes the destructor automatically before it dies. because Malloc/free is a library function and not an operator, the task of executing constructors and destructors cannot be imposed on malloc/free, not within the control of the compiler.
Therefore, the C + + language requires an operator new that can perform dynamic memory allocation and initialization, and an operator delete that can perform cleanup and deallocation work. Note New/delete is not a library function.
We should not attempt to use Malloc/free to complete the memory management of dynamic object, should use New/delete. Because the "objects" of the internal data types do not have a process of construction and destruction, Malloc/free and new/delete are equivalent to them.
3) Since the function of new/delete completely covered the Malloc/free, why C + + does not put malloc/free out of the elimination? This is because C + + programs often call C functions, whereas C programs can only use Malloc/free to manage dynamic memory.
If you release the dynamic object created by new with free, the object can cause a program error because it cannot execute the destructor. If you use Delete to release the dynamic memory for malloc requests, the result can also cause the program to fail, but the program is poorly readable. So new/delete must be paired and malloc/free the same.



The difference between malloc and new

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.