Tuesday, 25 November 2014

Memory allocation, de-allocation using new and delete with examples and syntax


New and Delete in C++:

Memory allocation, de-allocation using new and delete:

The new operator is used to create the object dynamically. Using the new operator the memory is allocated and the constructor of the class gets called for that memory.

Using the delete the destructor of the class gets called and the memory is released which is allocated by new.

Syntax for the new operator:
MyCls *pcClass = new MyCls;

Allocating the memory for the array of class objects:

MyCls *pcClass = new MyCls[10];

Syntax for the delete:
delete pcClass;
delete []pcClass;
delete pcClass - frees the memory for an individual object allocated by new.
delete []pcClass - frees the memory for an array of objects allocated by new.


How to allocate and de-allocate the memory for the array of objects:  
For arrays, a constructor must be called for each object in the array.
MyCls *pcClass = new MyCls[10];

The code calls operator new[] to allocate memory for 10 pcClass object, then call the default MyCls constructor for each array element.

In the way, when the delete operator is used on an array, it calls a destructor for each array element and then calls operator delete[] to de-allocate the memory.

It calls the string destructor for each array element, then calls operator delete[] to de-allocate the array's memory.

delete []pcClass; 

The above statement delete array created on the heap.
Let us have a look at the below example to understand more about the new and delete operators.

using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
class MyClsArray
{
public:
 MyClsArray()
 {
  std::cout << "I am in the default constructor" << std::endl;
 }
 MyClsArray(int s)
 {
    m_pdblArr = new double[s];
  std::cout << "I am in the parameterized constructor" << std::endl;
  for (int i = 0; i < s; ++i)
        m_pdblArr[i] = 0;
 }
 ~MyClsArray ()
 { 
    std::cout << "I am in the destructor" << std::endl;
  delete[] m_pdblArr;
 }
private:
 double *m_pdblArr;
};
int _tmain (int argc, _TCHAR* argv[])
{
  MyClsArray *myObj = new MyClsArray(10); 
 delete myObj;
  getchar ();
  return 0;
}
The output of the program is shown below:
I am in the parameterized constructor
I am in the destructor
The problem that we get if we do not delete the array of elements, some compilers, only the destructor for the 0th element of the array will be called because the compiler only knows that you are deleting a pointer to an object If we do not use the array.

The destructors are only called if the elements of the array are plain objects, however, if we have an array of pointers, we will still need to delete each element individually just as you allocated each element individually, as shown in the following code:
int _tmain (int argc, _TCHAR* argv[])
{
  int iSize = 10;
  MyClsArray **myObjArr = new MyClsArray*[iSize]; 
 /* Allocate an object for each pointer. */
 for (int iIndex = 0; iIndex < iSize;iIndex++)
  myObjArr[iIndex] = new MyClsArray();
 // Delete each allocated object.
 for (int i = 0; i < iSize; i++)
  delete myObjArr[i];
 // Delete the array itself.
 delete[] myObjArr;
  getchar ();
  return 0;
}
I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the default constructor

I am in the destructor

I am in the destructor

I am in the destructor

I am in the destructor

I am in the destructor

I am in the destructor

I am in the destructor

I am in the destructor

I am in the destructor

I am in the destructor


Initializing Dynamically Allocated Objects
 char *pcStr = new char;     // pcStr points to an unitialized int
 char *pcStr = new char() ;    // pcStr points to an integer initialized 0
  char ch;                   // named but not initialized int variable
 char *pchVal = new char;       // pi is pointer to a dynamically allocated
                   // unnamed and not initialized int
  int iVal(30);              // value of i is 30
 int *piVal = new int(30);  // piVal is pointing to an object whose value is 30
 MyClsArray ocArr (5);              
 MyClsArray *pcArr = new MyClsArray(25);
 MyClsArray *pcArr1 = new MyClsArray();

What is the Free Store?

What is the difference between the C & C++ free store?

In C there is no concept of new and delete operators.
To use the free store it uses malloc / calloc/ realloc functions.
Refer the topic of
Memory Management functions malloc(), calloc(), and realloc() with examples 

Why does malloc() return a void*?

The malloc() has no idea which type of object we want to put in that memory.
In case of C++, after we define a constructor, we can write:
 MyClsArray *myObj = new MyClsArray(10); 


No comments: