Suppose you are making a C++ program to store a particular number (specified by the user at runtime) of phone numbers. What will you do? You cannot declare array of 10 or 20 elements because you don’t know how many numbers the user will enter. He may want to enter 1, 10 or even 100 phone numbers.
So what will you do?
Actually, you can do two things to achieve this, that are listed below:
-
You can create a very large int(eger) array (say, of 500 elements) , in this case whether the user wants to store 1 or 500 phone numbers, the memory used will always be the same (large!).
-
You can make use of C++’s dynamic memory allocation to allocate only the needed amount of memory.
The first choice is a very bad way of programming, nevertheless it works fine, you should never employ such an inefficient method of programming.
So, you are left with only one choice to use the Dynamic Memory Allocation of C++ programming language, that I will be discussing in this article.
As is clear from the above example, dynamic memory allocation is needed when you don’t know the program’s memory needs beforehand.
Allocating Memory
Dynamic memory is allocated by the new keyword. Memory for one variable is allocated as below:
ptr=new DataType (initializer);
Here,
-
ptr is a valid pointer of type DataType.
-
DataType is any valid c++ data type.
-
Initializer (optional) if given, the newly allocated variable is initialized to that value.
Ex.
//Example Program in C++ #include<iostream.h> void main(void) { int *ptr; ptr=new int(10); cout<<*ptr; delete ptr; }
This is will allocate memory for an int(eger) having initial value 10, pointed by the ptr pointer.
Memory space for arrays is allocated as shown below:
ptr=new DataType [x];
Here,
-
ptr and DataType have the same meaning as above.
-
x is the number of elements and C is a constant.
Ex.
//Example Program in C++ #include<iostream.h> void main(void) { int *ptr, size; cin>>size; ptr=new int[size]; //arrays are freed-up like this delete []ptr; }
Freeing-Up Allocated Memory
Unlike static variables, c++ will not free-up the memory allocated through dynamic allocation. Its your duty to free them up. delete keyword is used to free-up the allocated memory.
delete ptr;
Arrays are deleted in a slightly different manner as shown below:
delete []ptr;
It’s easy to forget to free the allocated memory because C++ compiler won’t inform you that you are doing this. It’s your job and should always be done.
Now let me show you an example of dynamic memory allocation in action:
//Example Program in C++ #include<iostream.h> void main(void) { int *ptr, size; cout<<"How many PH. Numbers do you wish to enter:"; cin>>size; ptr=new int[size];//allocate memory //input ph. numbers for (int i=0;i<size;i++) { cout<<"Enter PH. NO."<<i+1<<" :"; cin>>ptr[i]; } //output ph. numbers cout<<"\n\n\n PH. NOs. are\n"; for (i=0;i<size;i++) cout<<"\nPH. NO."<<i+1<<" :"<<ptr[i]; cout<<endl; delete []ptr;//free-up memory }
Good-Bye!
Related Articles: