Dynamic Allocation

Dynamic allocation means allocating (or giving) and freeing memory at run time. The two operators used for this purpose are : new and delete.
New is used to allocate memory while delete is used to free the allocated memory (memory which was allocated by new). The free memory available is sometimes referred to as the heap. Memory that has been allocated by new should be freed by using delete. If you don't use delete then the memory becomes a waste and cannot be used by the system. This is called memory leak (i.e. when allocated memory is never returned to the heap).
Syntax :
data type * name = keyword new data type;
delete name ;
Note : Both data types should be the same.
Example :
int * p = new int;
delete p;

The new and delete operators are very useful when dealing with arrays. Let's consider an example :
void main ( )
{
int size,i;
cout<<"Enter the size of the array : ";
cin>>size;
int * marks = new int[size];
for (i = 0; i<size; i ++)
{
cin>>marks[i];
}
cout<<"The marks you entered are : "
for (i = 0; i<size; i ++)
{
cout<<marks[i];
}
delete [ ] marks;
}
marks is an array of integer type whose size is determined by
the user. If the user types 3, then the size of marks array is 3. The array has
been allocated using new operator. We get the input of the array using a for
loop and then we display the entered value using another for loop.
After having used the array we free up the memory space using delete. Since we are freeing up space used by an array, we have to free up space used by each element of the array. The syntax to free up the space is :
delete [ ] name of array;
The point is that you have to use the square brackets when dealing with arrays.

The next section will deal with Difference between void main ( ) and int main ( )
or you can go back to Contents page 2.