answersLogoWhite

0


Best Answer

1: new operator automatically computes the size of the data object. You need not use the operator sizeof.

2: new operator automatically returns the correct pointer type, so that there is no need to use a type cast.

3: it is possible to initialize the object while creating the memory space.

4: Like any other operator, new and delete can be overloaded.

User Avatar

Wiki User

12y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

14y ago

- Its the standard for object allocation in C++

- It supports strong type checking

- it has 3 characters less to type

- you dont need the typeof function as an argument (saves even more characters)

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

new calls constructor of classes and delete calls deconstructor. malloc and free dont.

also the syntax is hard with malloc

eg. malloc(int) sizeof(int) or whatever

while int * x;

x= new int(9)

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

The malloc function was inherited from C and is only required for backward compatibility with C.

The main disadvantage of malloc over the C++ new operator is that you cannot instantiate C++ objects using malloc, you can only instantiate primitive data types or POD data types; plain old data or trivial class/struct data types that behave as if they were C-style structs. Attempting to use malloc to instantiate a C++ object will result in undefined behaviour because the memory allocated to the pointer will be in an uninitialised state. That is, no constructors are invoked. Even if you can somehow initialise the data, when you subsequently free the pointer, the destructor will not be invoked, which means any resources allocated to the underlying object will not be released. The onus is therefore entirely upon the programmer to ensure all allocated resources are released before freeing any pointer to a C++ object. Even if you can manage all that by yourself, there huge are type-safety concerns, particularly when dealing with derived classes and virtual function tables. In short, there be dragons -- so don't go there.

Although you can use malloc when working with PODs and primitive data types, it really makes no sense to do so. For instance, malloc does not know how much memory to actually allocate to a particular object so you must manually tell it how much you need. In addition, the returned pointer is a void pointer, which means you must statically cast to the appropriate type. That's a lot of unnecessary work and is, ultimately, a distraction.

The new operator, on the other hand, can be used with any C or C++ data type, whether primitive, built-in or user-defined. If a non-null pointer is returned from the new operator, then the memory is guaranteed to be allocated and initialised according to whichever constructor was invoked (including any base class constructors) and is completely type-safe.

For primitive data types, there is no guarantee the memory is initialised unless you pass a value to the type's constructor, which is akin to initialising a variable at the point of instantiation. To ensure consistency when porting code to another compiler, always initialise pointers to primitive data types.

Note that although primitive data types are not implemented as objects (as they are in Java, for instance), C++ does allow object-construction syntax for any data type. This is merely sugar-coating to provide a consistent method of object construction.

Once you have a valid pointer, you can work with it just as you would a static object, except you use the pointer-to-member operator (->) instead of the member-of operator (.) to access the object's members.

Finally, when you delete a pointer allocated with new, you automatically invoke the object's destructor, including any base class destructors, which (if programmed correctly) will automatically release any and all resources allocated to the object.

In short, the onus with regards resource management is placed entirely upon the object itself. The programmer need not concern themselves with how resources are allocated and destroyed; they simply instantiate a pointer with new, use the pointer according the underlying object's interface, and delete the pointer when they are finished with it. The only things the programmer has to remember is to delete every pointer allocated with the new operator and to assign the nullptr object to any and all pointers that are not currently in use to ensure they are properly initialised. Remember C++ has no automatic garbage collection. All resources allocated by you with the new operator are your responsibility and yours alone.

Note that although resource management is much simpler with the new operator than with malloc, it's still best to avoid using new wherever you possibly can. Statically allocated objects always clean up after themselves, automatically, as soon as they fall from scope and are generally much easier to work with. Use the new operator only when static allocation is not feasible. In this way, you'll have far fewer resources to manage, which minimises the risk of leaked memory. Also, if you need to manage a lot of resources, wrap them in one or more classes and let the classes handle the resource management for you. In this way you need only instantiate static instances of those classes while the instances themselves manage the resources Behind the Scenes.

This answer is:
User Avatar

User Avatar

Wiki User

7y ago

We never use the malloc() function in C++ unless we're actually writing C code. When we allocate memory we typically want to place one or more initialised objects in that memory, which means the class constructor for each object must be invoked automatically. But the malloc() function is a C function and C knows nothing about classes let alone constructors, so when we allocate memory all we get is the (uninitialised) memory itself; there are no valid objects allocated to that memory. This means we must use placement new in order to construct those objects in the allocated memory, but there is no equivalent of placement new in C.

In C++ the malloc() function behaves exactly as it does in C except that the returned pointer must be explicitly cast to the appropriate type. Consider the following usage:

int* p = (int*) malloc ( sizeof (int));

if (p==nullptr) throw std::bad_alloc ();

*p = 42;

Now consider the equivalent code using operator new:

int* p = new int {42};

This single line does everything those three lines of C-style code do, including automatically throwing an exception if the allocation should fail. This means that if the exception is not thrown by operator new, p is guaranteed to point to a valid, initialised object of type int.

The operator new functions are all defined in the C++ header as follows:

  1. void* operator new (std::size_t);
  2. void* operator new [] (std::size_t);
  3. void* operator new (std::size_t, const std::nothrow_t&) noexcept;
  4. void* operator new [] (std::size_t, const std::nothrow_t&) noexcept;

These four are known as the replaceable allocation functions. Note that there are two versions of each operator, one for single objects and another for arrays of objects. The first two operators will throw a std::bad_alloc object (or one of its derivatives) upon failure while the last two will return a nullptr on failure. All four are implicitly declared in every C++ translation unit whether we include the header or not.

In addition, we also have two placement new operatorswhich are used specifically to instantiate objects in memory that has already been allocated (including memory allocated via the malloc() function):

  1. void* operator new (std::size_t size, void* ptr) noexcept;
  2. void* operator new [] (std::size_t size, void* ptr) noexcept;

We can use the placement new operator to instantiate objects in memory already allocated on the stack or in static memory as well as on the heap. Note that the malloc()function can only allocate memory on the heap.

Moreover, we can overload the placement new operators:

  1. void* operator new ( std::size_t count, user-defined-args... );
  2. void* operator new [] ( std::size_t count, user-defined-args... );

In addition, we can provide class-specific overloaded operators:

  1. void* T::operator new ( std::size_t count );
  2. void* T::operator new [] ( std::size_t count );
  3. void* T::operator new ( std::size_t count, user-defined-args... );
  4. void* T::operator new [] ( std::size_t count, user-defined-args... );

Combined, these new operators give us fine-grained control over the instantiation of our objects ensuring that whenever we hold a pointer to an object, we can be sure the object being pointed at is in a valid state (assuming its constructors are well-defined of course). We have no such guarantees with the malloc() function.

In practice we seldom use the new operators. Pointers to heap allocations are a constant source of bugs and resource leaks, so we try to avoid using them as much as is practical. We cannot avoid them completely of course, however we can easily hide pointers in resource handles such as std::vector. Arrays of pointers to a type T are a common construct in C but in C++ we can use a std::vector>instead.

This answer is:
User Avatar

User Avatar

Protik Sarkar

Lvl 2
2y ago

# Advantages of using NEW over MALLOC() are:-

1.operator new can be overloaded, malloc cannot be overloaded.

2.operator new is an operator , malloc is a function.

3)operator new throws an exception if there was not enough memory , malloc returns null.

4)operator new constructs an object (calls constructor of object), malloc does not.

5)operator new/new[] must be matched with operator delete/delete[] to deallocate memory,malloc() must be matched with free() to deallocate() memory.

6)operator new() requires to specify the number of objects to allocate, malloc requires to specify the total number of bytes to allocate.

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

They are the same, and are often versions of the same routine. The difference is that operator new also invokes the constructor.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

1. You cannot use 'delete' in C.

2. Even if you could, 'delete' and 'malloc' are completely different things.

This answer is:
User Avatar

User Avatar

Wiki User

14y ago

Allocates memory.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Advantages of new operator over malloc function in c?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Which is preffered in C malloc or new why?

C does not have a new operator, so we must use the malloc function.In C++ we prefer the new operator over malloc. The new operator not only allocates memory to an object, it invokes that object's constructor, thus ensuring correct initialisation of the object, thus establishing the object's invariant (if it has one). If construction fails for any reason, an exception will be thrown and no object will be instantiated. If the class designer has made correct use of resource acquisition is initialisation(RAII), any resources consumed by the constructor prior to throwing the exception will be automatically returned to the system, thus ensuring no resource leaks occur.The sole purpose of malloc is to allocate memory and nothing more. If the allocation fails, a null pointer is returned, otherwise the start address of the allocation is returned. However, the memory is left in an uninitialised state even if the object has a constructor. Moreover, neither malloc, calloc nor realloc will throw exceptions so they are unsuitable for enabling RAII. The only reason they exist at all in C++ is simply for the sake of backward compatibility with C code which cannot use the new operator (since it does not exist in C).


When operator function is declared as friend function?

Ideally, never. Friend functions should only be employed when a function (whether an operator overload or not) requires private access to a class, and it is not otherwise possible to provide a public interface without unduly undermining the class encapsulation. However, as programmer, it is your responsibility to ensure all friend functions adhere to the same class rules (which you yourself define) as do the members of your class, even though friends are not regarded as being members of the class. Ultimately, if you have no control over the friend function implementation, then you must not allow that function to be a friend of your class, as this will seriously undermine the encapsulation.


Need for going to standard library functions instead of low level functions in linux?

Just use what you want; if you prefer brk(2) over malloc(3), do use it.


What is the use of arrays over pointers?

Arrays can be regarded as constant pointers. Example: int *pi, ai[5]; pi= ai; /* okay */ pi[0]= ai[0]; /* okay */ ai[0]= pi[0]; /* okay */ pi= (int *)malloc (10*sizeof (int)); /* okay */ ai= pi; /* NOT okay */ ai= (int *)malloc (10*sizeof (int)); /* NOT okay */


What are the advantages of a hovercraft?

The Advantages are that Hovercraft can fly, or more suitably, hover over water and land, can go over rough terrain and does not pollute as much as cars.

Related questions

Comparison of C' malloc and free functions with c new and delete operators?

Hi, The difference between new and malloc: 1.The New is a operator however malloc is a function 2.New returns the object type and there is no typecasting required. In malloc type casting should be done as it returns a void*. 3. The new operator can be overloaded however there is no over loading in C and hence Malloc can not be overloaded. 4. Operater New asks for the number of objects to be allocated however in malloc it will ask you for the number of bytes to be allocated. 5. The New operater will return you a exception of memory is not available however in malloc it will return u a NULL. 6. New is a concept for dynamically allocation in OOPS(C++) however malloc is used in C. The difference between the delete and free is as follows: 1. delete is a operator and can be overloaded however free is a function and can not be overloaded. With Regards, Shashiraja Shastry


Which is preffered in C malloc or new why?

C does not have a new operator, so we must use the malloc function.In C++ we prefer the new operator over malloc. The new operator not only allocates memory to an object, it invokes that object's constructor, thus ensuring correct initialisation of the object, thus establishing the object's invariant (if it has one). If construction fails for any reason, an exception will be thrown and no object will be instantiated. If the class designer has made correct use of resource acquisition is initialisation(RAII), any resources consumed by the constructor prior to throwing the exception will be automatically returned to the system, thus ensuring no resource leaks occur.The sole purpose of malloc is to allocate memory and nothing more. If the allocation fails, a null pointer is returned, otherwise the start address of the allocation is returned. However, the memory is left in an uninitialised state even if the object has a constructor. Moreover, neither malloc, calloc nor realloc will throw exceptions so they are unsuitable for enabling RAII. The only reason they exist at all in C++ is simply for the sake of backward compatibility with C code which cannot use the new operator (since it does not exist in C).


What are the advantages of the new operator?

The new operator in programming is used to allocate memory for a new object or instance of a class. It helps in dynamic memory allocation and object creation at runtime, allowing for flexible memory management and object instantiation in languages like Java and C++.


What are the advantages of TTL over DTL?

because the amplifying function are performed by transistors (contrast with RTL and DTL).


What advantage does a radio telescope have over a optical telescope?

They function on entirely different principles. it is like asking what advantages does a parabolic sound detector ( a common spy device that looks like, but is not radar oriented) have over a pair of binoculars. one records sound or radio wavelengths, the other visual images. They have totally different applications one has a telescope operator as an observer, visually observing targets but the radio-telescope operator is merely a monitor. the analogy with radar is good as they are a derivative of Radio Direction and Ranging, hence RADAR,


When operator function is declared as friend function?

Ideally, never. Friend functions should only be employed when a function (whether an operator overload or not) requires private access to a class, and it is not otherwise possible to provide a public interface without unduly undermining the class encapsulation. However, as programmer, it is your responsibility to ensure all friend functions adhere to the same class rules (which you yourself define) as do the members of your class, even though friends are not regarded as being members of the class. Ultimately, if you have no control over the friend function implementation, then you must not allow that function to be a friend of your class, as this will seriously undermine the encapsulation.


What are advantages of hartnell over porter governor?

advantages of hartnell governor over porter governor


What does 1 over 16 1 over 18 equal?

Missing symbol (operator).


What advantages do corporations have over small businesses?

List two advantages that corporation have over a small business


What advantages does the iPod Nano have over the iPod Touch?

No advantages whatsoever...


What is operator over loading?

Same operator can be used for different purposes like + can be used for addition of two integers and used for concatenate strings.


What are the advantages of PowerPoint presentations over the other presentation methods?

what are the advantages of powerpoint over the other presentation method