Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Elaborate 10-point difference between the new and malloc     - Java enum use (Programming)

- Summarize small problems encountered in the use Lua (Programming)

- Linux process management related content (Linux)

- Installation and use the telnet command under CentOS 6.x (Linux)

- Ubuntu Install OpenSSL (Linux)

- Linux virtual machines to solve end MySQL database can not remote access (Database)

- Vi (Vim) keyboard map and its basic commands (Linux)

- Linux directory permissions to read and execute permissions difference (Linux)

- Use Tails 1.4 Linux system to protect the privacy and anonymity (Linux)

- Linux system components Detailed log (Linux)

- Subquery Oracle study notes (Database)

- Git Getting Started tutorial (Linux)

- SUSE Firewall Configuration (Linux)

- Large site architecture study notes (Server)

- Linux environment variable configuration and save places (Linux)

- Kernel compile under Debian (Linux)

- Use lsof restore accidentally deleted log files or database (Linux)

- Oracle 12C truncate table cascade (Database)

- Setting CentOS firewall open port (Linux)

- Guide: Trickle restrict application bandwidth usage (Linux)

  Elaborate 10-point difference between the new and malloc
  Add Date : 2018-11-21      

A few weeks went to interview C ++ development internship position, the interviewer asked a question:

new and malloc What is the difference?

This is a commonplace problem. At that time I answer new to allocate memory from the free store, malloc to allocate memory from the heap; new / delete calls the constructor / destructor to initialize and destroy objects; operator new / delete can be overloaded; then analyzes the force about the difference between free store and stack. Came back feeling really answer this question Debu how good, because the distinction between new and malloc actually a lot. During the interview it happens just finished final exams, followed by several course set no time to organize. Today, we spend some time to sort this problem.

10-point difference between the new and malloc

1. Application of the memory location

new operator from the free store (free store) on the dynamic allocation of memory space for the object, while malloc function to dynamically allocate memory from the heap. Free store is based on the C ++ new operator of an abstract concept, all for memory application using the new operator, the memory is free store. The heap is the operating system terms, the operating system is maintained by a special memory, dynamic memory allocation for the program, C language using malloc to allocate memory from the heap, using the free release allocated memory correspondence.

So if free store can be a heap (equivalent to the question whether the new energy in the heap dynamically allocated memory), depending on the operator new implementation details. Free store not only heap may also be a static memory, which can not see where the operator new to allocate memory for the object.

In particular, new and even can not allocate memory for the object! Positioning new features can do this:

new (place_address) type
place_address as a pointer representative of a memory address. When using the above address to call this only a new operator, new operator to call a specific operator new, this version is the following:

void * operatornew (size_t, void *) // not allowed to redefine this version of operator new
The operator new does not allocate any memory, it simply returns a pointer argument, then right-click the new expression is responsible place_address specified address object initialization.

2. Return the type of security

When the new operator memory allocation succeeds, the return type is a pointer to the object, and the object type of strict matching, without the need for conversion, so the new type of security is in line with the operator. The malloc memory allocation is successful return void *, need to cast the void * pointer into the type that we need.
Type safety can be largely equivalent to the memory security, type-safe code does not attempt memory area method I had not been authorized. About C ++ type safety have a lot to say.

Return value 3. Memory allocation failure when

When the new memory allocation fails, an exception will be thrown bac_alloc, it does not return NULL; returns NULL when malloc to allocate memory failed.
When using the C language, we used malloc memory allocation is determined after the allocation is successful:

int * a = (int *) malloc (sizeof (int));
if (NULL == a)
C ++ into the camp from the C language novice may put this habit into C ++:

int * a = new int ();
if (NULL == a)
In fact, doing so does not make sense, because the new will never return NULL, and the program can be executed if the statement has been explained to the memory allocation is successful, if it fails a long throw exception. The correct way is to use the exception mechanism:

    int * a = new int ();
catch (bad_alloc)

4. Do you need to specify the size of memory

Without specifying when the new operator application memory allocation size of the memory block, the compiler will own calculations based on the type of information, it should be noted that malloc explicitly required memory size.

class A {...}
A * ptr = new A;
A * ptr = (A *) malloc (sizeof (A)); // need to explicitly specify the required memory size sizeof (A);
Of course, I am here for us to use malloc to allocate memory for custom type is not very suitable, look at the next one.

5. Do you call the constructor / destructor

Using the new operator will be allocated through three steps Object Memory:

The first step: call operator new function (for arrays is operator new []) allocate a large enough, the original, so that a particular type of object storage unnamed memory space.
Step two: Run the appropriate compiler constructor to construct the object and pass the initial value.
Part III: The object construction is complete, return a pointer to the object.
Go through two steps using the delete operator to release the object memory:

The first step: call the object's destructor.
Step two: the compiler calls operator delete (or operator delete []) function to release memory space.
In short, the constructor new / delete calls the object / destructors to accomplish the object constructor / destructor. The malloc is not. If you are never too long-winded can look my example:

class A
    A (): a (1), b (1.11) {}
    int a;
    double b;
int main ()
    A * ptr = (A *) malloc (sizeof (A));
    return 0;

Set a breakpoint at the return point, viewing the content within the meaning of memory ptr

A default constructor can be seen and is not called because the data members of a, b values have not been initialized, which is why I said above, use malloc / free to handle custom type C ++ inappropriate, in fact, more than custom type, standard library who need construction / type destructor of all inappropriate.

Used to allocate new objects:

int main ()
    A * ptr = new A;
Check the assembly code generated by the program can be found, the default constructor is called A

6. array processing

C ++ provides a new [] and delete [] to deal specifically with the array type:

    A * ptr = new A [10]; // allocate 10 A target
Using new [] allocated memory must use the delete [] be released:

    delete [] ptr;
new array of support calls are reflected in its constructor function to initialize each array element, when the release of the object for each object to calling the destructor. Note that delete [] to the new [] supporting the use of, or be part of an array of objects to find release phenomenon, causing a memory leak.

As malloc, you know it and to put on a piece of memory array or something else, anyway, it gives you a raw memory, giving you a memory address on the bin. So if you want an array of dynamic memory allocation, we also need to manually customize the size of the array:

int * ptr = (int *) malloc (sizeof (int)); // allocate an array of 10 int elements

Are 7.new with malloc can call each other

operator new / operator delete implementation can be based on malloc, and malloc implementations can not go calling new. Here is a simple way to write operator new / operator delete the other versions Similarly:

void * operatornew (sieze_t size)
    if (void * mem = malloc (size)
        return mem;
        throw bad_alloc ();
voidoperatordelete (void * mem) noexcept {
    free (mem);
8. Can be overloaded

opeartor new / operator delete can be overloaded. The standard library is defined eight overloaded version of operator new and operator delete functions function:

// These versions may throw an exception
void * operatornew (size_t);
void * operator new [] (size_t);
void * operatordelete (void *) noexcept;
void * operator delete [] (void * 0) noexcept;
// These versions promise not to throw an exception
void * operatornew (size_t, nothrow_t &) noexcept;
void * operator new [] (size_t, nothrow_t &);
void * operatordelete (void *, nothrow_t &) noexcept;
void * operator delete [] (void * 0, nothrow_t &) noexcept;
We can customize the function version of the above any one, as long as the custom version must be in the global scope or class scope. Too much detail here about something that is not, in short, we know that we have the freedom to overloaded operator new / operator delete, to decide how our new and delete to allocate memory for the object, how to recycle the object.

The malloc / free does not allow overloading.

9. can intuitively reallocate memory

After using malloc allocation of memory, if found to be insufficient memory in use, you can use the realloc function memory reallocation implement memory expansion. realloc first determine whether the current pointer memory have enough contiguous space, if any, can be allocated in situ expanded memory address, and returns the old address pointer; if the space is not enough, according to the newly specified size of the allocated space, the original from beginning to end data copied to the newly allocated memory area, and then release the original memory area.

Without such an intuitive new facilities to expand the memory.

10. The lack of customer handles memory allocation

Before the operator new throws an exception to reflect an unmet need, it will first call a user-specified error-handling function, which is the new-handler. new_handler is a pointer type:

namespace std
    typedefvoid (* new_handler) ();
No argument points to a function that returns no value, that is, the error handler. To specify the error handling function, customers need to call set_new_handler, which is a standard library function in a statement of:

namespace std
    new_handler set_new_handler (new_handler p) throw ();
set_new_handler parameters for the new_handler pointer to a function when the operator new can not allocate enough memory for the call. The return value is a pointer pointing to set_new_handler before being executed is called the new_handler function (but soon replaced incurred).

For malloc, customers are not able to determine when the programming is insufficient memory allocated to doing things, can only watch malloc returns NULL.

to sum up

The 10-point difference between the above-organized into tables:

Feature new / delete malloc / free
Allocate memory location free store heap
Memory allocation failure complete return value type pointer to void *
Memory allocation failed to return the default value of an exception return NULL
Allocate memory size obtained must explicitly specify the number of bytes by the compiler according to the type of calculation
Memory allocation process post-processing array has an array of new versions of new [] require the user to calculate the size of the array
Expansion of allocated memory can not be intuitively simple to complete processing uses realloc
If you can call each other, see the specific operator new / delete can not implement new call
Insufficient memory customers can specify the handler allocating memory or re-enacted the distributor can not be handled by user code
Function overloading allows not allowed
The constructor and destructor calls do not call
malloc gives you is like a primitive land, you have to kind of what it takes to own land sown up

The new plan to help you land a good block (array), to help you seeded (constructor), also provides other facilities for your use:

Of course, malloc is not to say not as new, they each have suitable places. This emphasis on OOP in C ++ language, using new / delete is naturally more appropriate.
- Kafka + Log4j log implement centralized management (Server)
- Go powerful development server simple example (Server)
- Ubuntu install perfectly handsome terminal Guake 0.8.1 (Linux)
- To install MySQL on Linux (Database)
- To install Samba server on CentOS 6.6 (Server)
- Ubuntu 14.04 LTS 64-bit installation and activation Sublime Text 3 can not solve the Chinese input method to solve the problem (Linux)
- Ubuntu and Derivative Edition users install LMMS 0.4.15 (Linux)
- How do you turn on and off IPv6 address on Fedora (Linux)
- Ubuntu Gitolite management Git Server code base permissions (Server)
- Teach you how to ensure password security under the Linux operating system (Linux)
- MongoDB relations, references, index query coverage (Database)
- Ubuntu 14.04 LTS NTFS partition can not access solution (Linux)
- RHEL6.4 x86_64 build SVN service (Server)
- Ubuntu install snmp packets Unlinked OID in IPATM-IPMC-MIB: marsMIB (Linux)
- Migrate Oracle database files to ASM (Database)
- Installation of Python2.7.8 and iPython under CentOS6.5 (Linux)
- Encounter ORA-00600: internal error code, arguments: [4194] ORA-1552 (Database)
- Recent Consolidation Using Linux security module (Linux)
- About Python default character set (Linux)
- Configure the Linux kernel and use iptables to do port mapping (Linux)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.