Login    New User    Forgot Password    Help      

Dynamic Memory


Dynamic Memory

Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime? For example, in the case that we need some user input to determine the necessary amount of memory space. The answer is dynamic memory, for which C++ integrates the operators new and delete. Operators new and new[] In order to request dynamic memory we use the operator new. new is followed by a data type specifier and -if a sequence of more than one element is required- the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form is: pointer = new type pointer = new type [number_of_elements] The first expression is used to allocate memory to contain one single element of type type. The second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example: int * roll_no; roll_no = new int [5];

Operators delete and delete[]

Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operatordelete, whose format is:

delete pointer;

delete [] pointer;

The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements. 

The value passed as argument to delete must be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).

Example Programe

#include <iostream>

#include <new>

int main ()


int i,n;

int * p;

cout << "How many numbers would you like to type? ";

cin >> i;

p= new (nothrow) int[i];

if (p == 0)

cout << "Error: memory could not be allocated";

else { for (n=0; n<i; n++)

{ cout << "Enter number: "; cin >> p[n]; }

cout << "You have entered: "; for (n=0; n<i; n++)

cout << p[n] << ", ";

delete[] p; }

return 0; }


How many numbers would you like to type? 5

Enter number : 75

Enter number : 436

Enter number : 1067

Enter number : 8

Enter number : 32

You have entered: 75, 436, 1067, 8, 32,

In this example without using loop it prints the number from 1 to 5,using goto statementcompiler goes to the start tag when goto statement encounters