new vs malloc delete

malloc() vs new

Following are the differences between malloc() and operator new.:

  1. Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10.
    filter_none

    edit

    play_arrow

    brightness_4

    #include<iostream>
      
    using namespace std;
      
    int main()
    {
       int *n = new int(10); // initialization with new()
       cout << *n;
       getchar();
       return 0;
    }
  2. operator vs function: new is an operator, while malloc() is a function.
  3. return type: new returns exact data type, while malloc() returns void *.
  4. Failure Condition: On failure, malloc() returns NULL where as new Throws.
  5. Memory: In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap.
  6. Overriding: We are allowed to override new operator where as we can not override the malloc() function legally.
  7. Size: Required size of memory is calculated by compiler for new, where as we have to manually calculate size for malloc().
NEWMALLOC
calls constructor doesnot calls constructors
It is an operator It is a function
Returns exact data type Returns void *
on failure, Throws On failure, returns NULL
Memory allocated from free store Memory allocated from heap
can be overridden cannot be overridden
size is calculated by compiler size is calculated manually

 

new and delete operators in C++ for dynamic memory

 

Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack (Refer Memory Layout C Programs for details).

What are applications?

  • One use of dynamically allocated memory is to allocate memory of variable size which is not possible with compiler allocated memory except variable length arrays.
  • The most important use is flexibility provided to programmers. We are free to allocate and deallocate memory whenever we need and whenever we don’t need anymore. There are many cases where this flexibility helps. Examples of such cases are Linked ListTree, etc.

How is it different from memory allocated to normal variables?
For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and deallocated. For dynamically allocated memory like “int *p = new int[10]”, it is programmers responsibility to deallocate memory when no longer needed. If programmer doesn’t deallocate memory, it causes memory leak (memory is not deallocated until program terminates).

How is memory allocated/deallocated in C++?
C uses malloc() and calloc() function to allocate memory dynamically at run time and uses free() function to free dynamically allocated memory. C++ supports these functions and also has two operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.

This article is all about new and delete operators.

The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

  • Syntax to use new operator: To allocate memory of any data type, the syntax is:
    pointer-variable = new data-type;
    

    Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user defined data types including structure and class.
    Example:

    // Pointer initialized with NULL
    // Then request memory for the variable
    int *p = NULL; 
    p = new int;   
    
                OR
    
    // Combine declaration of pointer 
    // and their assignment
    int *p = new int; 
    
  • Initialize memory: We can also initialize the memory using new operator:
    pointer-variable = new data-type(value);
    Example:
    int *p = new int(25);
    float *q = new float(75.25);
    
  • Allocate block of memory: new operator is also used to allocate a block(an array) of memory of type data-type.
    pointer-variable = new data-type[size];
    

    where size(a variable) specifies the number of elements in an array.

    Example:
            int *p = new int[10]
    

    Dynamically allocates memory for 10 integers continuously of type int and returns pointer to the first element of the sequence, which is assigned to p(a pointer). p[0] refers to first element, p[1] refers to second element and so on.
    dynamic

Normal Array Declaration vs Using new
There is a difference between declaring a normal array and allocating a block of memory using new. The most important difference is, normal arrays are deallocated by compiler (If array is local, then deallocated when function returns or completes). However, dynamically allocated arrays always remain there until either they are deallocated by programmer or program terminates.

What if enough memory is not available during runtime?
If enough memory is not available in the heap to allocate, the new request indicates failure by throwing an exception of type std::bad_alloc, unless “nothrow” is used with the new operator, in which case it returns a NULL pointer (scroll to section “Exception handling of new operator” in this article). Therefore, it may be good idea to check for the pointer variable produced by new before using it program.

int *p = new(nothrow) int;
if (!p)
{
   cout << "Memory allocation failed\n";
}

delete operator

Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++ language.
Syntax:

// Release memory pointed by pointer-variable
delete pointer-variable;  

Here, pointer-variable is the pointer that points to the data object created by new.
Examples:

  delete p;
  delete q;

To free the dynamically allocated array pointed by pointer-variable, use following form of delete:

// Release block of memory 
// pointed by pointer-variable
delete[] pointer-variable;  

Example:
   // It will free the entire array
   // pointed by p.
   delete[] p;

// C++ program to illustrate dynamic allocation 
// and deallocation of memory using new and delete 
#include <iostream> 
using namespace std; 

int main () 
{ 
	// Pointer initialization to null 
	int* p = NULL; 

	// Request memory for the variable 
	// using new operator 
	p = new(nothrow) int; 
	if (!p) 
		cout << "allocation of memory failed\n"; 
	else
	{ 
		// Store value at allocated address 
		*p = 29; 
		cout << "Value of p: " << *p << endl; 
	} 

	// Request block of memory 
	// using new operator 
	float *r = new float(75.25); 

	cout << "Value of r: " << *r << endl; 

	// Request block of memory of size n 
	int n = 5; 
	int *q = new(nothrow) int[n]; 

	if (!q) 
		cout << "allocation of memory failed\n"; 
	else
	{ 
		for (int i = 0; i < n; i++) 
			q[i] = i+1; 

		cout << "Value store in block of memory: "; 
		for (int i = 0; i < n; i++) 
			cout << q[i] << " "; 
	} 

	// freed the allocated memory 
	delete p; 
	delete r; 

	// freed the block of allocated memory 
	delete[] q; 

	return 0; 
} 

  

posted on 2019-05-04 09:31  EMH1899  阅读(204)  评论(0编辑  收藏  举报

导航