The difference between new and malloc

Source: Internet
Author: User
Tags clear screen

Http://blog.sina.com.cn/s/blog_6fc5bfa90100qgd7.html
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 with 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.
3, so the C + + language requires an operator new that can perform dynamic memory allocation and initialization, with an operator delete that can perform cleanup and release of memory work. Note New/delete is not a library function.
4,c++ programs often call C functions, while C programs can only be managed with Malloc/free dynamic memory new is an operator, and what "+", "-", "=" ... Have the same status simple: Malloc,free is the function of C, New,delete is the C + + operator In addition, new is mandatory type, malloc is not, requires type conversion of course there are many different new can call the constructor at the time of declaration initialization malloc just allocates space, needs to be initialized somewhere else, and delete not only frees up space, it calls destructors before releasing, and malloc needs to specify the size of the allocation space, and new is automatically calculated

A collection of differences between new and malloc

1.New is an operator in C + + and malloc is a function in C

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 has three letters, and malloc has six letters.

New can be thought of as the execution of malloc plus constructors.

The new pointer is directly with the type information.

and malloc returns a void pointer.

A: New delete is an operator, Malloc,free is a function

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.

For objects of non-intrinsic data types, light Maloc/free cannot meet 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.

Let's take a look at how Malloc/free and new/delete implement dynamic memory management for objects, see example.

Class OBJ

{

Public:

Obj (void) {cout < < "initialization" << Endl;}

~obj (void) {cout < < "Destroy" << Endl;}

void Initialize (void) {cout < < "initialization" << Endl;}

void Destroy (void) {cout < < "Destroy" << Endl;}

};

void Usemallocfree (void)

{

obj *a = (obj *) malloc (sizeof (obj)); Request Dynamic Memory

a->initialize (); Initialization

//...

A->destroy (); Clear work

Free (a); Freeing memory

}

void Usenewdelete (void)

{

obj *a = new obj; Request dynamic Memory and initialize

//...

Delete A; Clear and free memory

}

Examples of how to implement dynamic memory management for objects with Malloc/free and New/delete

The function of the class obj initialize simulates the function of the constructor, and the function destroy simulates the function of the destructor. In function Usemallocfree, because Malloc/free cannot execute constructors and destructors, member functions initialize and destroy must be called to complete initialization and cleanup work. The function usenewdelete is much simpler.

Therefore, 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.

Since New/delete's function completely covers the Malloc/free, why does C + + not put Malloc/free out? 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 release "Dynamic Memory for malloc request" with delete, the program is theoretically not error-free, but the program is poorly readable. So New/delete must be paired and malloc/free the same.

Second: The new delete actually calls the Malloc,free function on the implementation.

Three: New operator also calls the constructor, in addition to allocating memory.

The malloc function is only responsible for allocating memory.

///////////////////////////////////////

New one-dimensional array

XXX *arr;
int Len; Dynamically determine the length value

arr = new Xxx[len]; Dynamically allocated, you can also use malloc
...
Delete[] arr; Don't forget to release


New multidimensional Array

It is a good practice to declare an n-dimensional array, each of which is a pointer to a char, and then allocate memory for each unit separately. The code is as follows

Char **array=new char*[n];
for (int i=0;i array[i]=new char[m];

Note: The above code should pay special attention when releasing allocated memory. Because this is a "deep memory allocation", the memory that is pointed to by the pointer in each cell is freed when it is released. Release the memory code as follows:

For (I=0;i delete[] array[i];
Delete[] Array;

malloc function
Prototype: extern void *malloc (unsigned int num_bytes);

Usage: #include <malloc.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.

Example:
Malloc.c

#include <syslib.h>
#include <malloc.h>
Main ()
{
Char *p;

CLRSCR (); Clear Screen
p= (char *) malloc (100);
if (p)
printf ("Memory allocated at:%x", p);
Else
printf ("Not Enough memory!\n");
Free (p);

GetChar ();
return 0;
}

function declaration (function prototype):
void *malloc (int size);
Description: malloc allocated memory space to the system to allocate a specified size byte. 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.
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 desired 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 compile, 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 homeless, 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.
Malloc can also achieve the effect of new [], requesting a contiguous amount of memory by specifying the size of the memory you need.
For example, to allocate 100 spaces of type int:
int* p = (int *) malloc (sizeof (int) * 100); Allocates a memory space that can be placed down to 100 integers.
Another thing that cannot be directly seen is that malloc allocates memory and does not initialize the resulting memory, so the value will be random in a new piece of memory.
In addition to the method of allocation and final release, pointers are obtained through malloc or new and are consistent on other operations.

Add a special case to it.
Char *ptr;
if (ptr = (char *) malloc (0)) = = NULL)
Puts ("Got a null pointer");
Else
Puts ("Got a valid pointer");
At this point, got a valid pointer is obtained. Assign 0 to Maclloc to get a valid pointer.


struct Hostent *hp;

Note is sizeof (STURCT hostent) rather than sizeof (STURCT hostent*)
where n represents the number of STURCT hostent type data you need
HP = (struct hostent*) malloc (N * sizeof (STURCT hostent));

if (!HP)//recommended to add this memory allocation success or not detection
{
How to add a memory allocation failure
}


New Delete, free malloc

The first thing you should know is that malloc and free are matched; New and delete are matches and they can't be confused.

malloc and new both apply for space, but new is a strongly typed assignment that invokes the object's constructor to initialize the object, whereas malloc allocates only memory space but does not initialize.

New adaptive type, malloc needs to cast new to allocate by type, malloc needs to specify memory size for an object, free does release the memory of the object, but does not call the object's destructor. Delete Not only frees the object's memory, but also invokes the destructor of the object so that the object is deleted with free in the object, and the memory may be leaked inside the delete still called free.

Add a point: Although both new and malloc apply for memory, but the location of the application is different, new's memory is allocated from the free store, and malloc's memory is allocated from the heap (see ISO14882 's Memory Management section for details), the free store and the heap are similar, are dynamic memory, but the locations are different, which is why new memory cannot be released through free. However, the Microsoft compiler does not have a good standard of implementation, it is possible to confuse the free store and heap, so free can sometimes.

Add: Delete does not need to check null

Delete NULL; There is no problem, so

if (p)

{

Delete p;

p = NULL;

}

Might as well

Delete p;

p = NULL;

and free (NULL) That's a lot of trouble.

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, light Maloc/free cannot meet 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.
The 3.c++ language requires an operator new that can perform dynamic memory allocation and initialization, and an operator delete that can perform cleanup and freeing of memory work. Note New/delete is not a library function.
Let's take a look at how Malloc/free and new/delete implement dynamic memory management for objects, as shown in example 7-8.
Class OBJ
{
Public:

OBJ (void) {cout << "initialization" << Endl;}
~obj (void) {cout << "Destroy" << Endl;}
void Initialize (void) {cout << "initialization" << Endl;}
void Destroy (void) {cout << "Destroy" << Endl;}
};
void Usemallocfree (void)
{obj *a = (obj *) malloc (sizeof (obj)); Request Dynamic Memory
A->initialize (); Initialization
... a->destroy (); Clear work
Free (a); Freeing memory
}
void Usenewdelete (void)
{
obj *a = new obj; Request dynamic Memory and initialize
.... delete A; Clear and free memory
}
Example 7-8 how to implement dynamic memory management of objects with Malloc/free and New/delete
The function of the class obj initialize simulates the function of the constructor, and the function destroy simulates the function of the destructor. In function Usemallocfree, because Malloc/free cannot execute constructors and destructors, member functions initialize and destroy must be called to complete initialization and cleanup work. The function usenewdelete is much simpler.

Therefore, 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.
4. Since New/delete's function completely covers the Malloc/free, why does C + + not eliminate Malloc/free? 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 release "Dynamic Memory for malloc request" with delete, the program is theoretically not error-free, but the program is poorly readable. So new/delete must be paired and malloc/free the same.

Several uses of 5.new:

int *p=new int; Open an int variable in a free storage area
int *p=new int[10];//opens an int array in free storage with 10 elements
int *p=new int (10);//Open an int variable in free storage and initialize it to 10

The difference between new and malloc

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.