Ad

Tuesday, June 19, 2007

Introduction to Dynamic Memory Allocation in C++

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:

  1. 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!).

  2. 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:

22 comments:

  1. Scilly_guy6:50 AM

    Ok but what if you want to use a two dimensional array, allocation would look something like

    int width(3), height(5);

    dataType** myArray=NULL;

    myArray=new dataType[width];

    for(int i=0;i less than width;++i)
    {
    myArray[i]=new dataType[height];
    }

    But what would deletion look like?
    I thought it should be the reverse:

    for(int i=0;i less than width;++i)
    {
    delete [] myArray[i];
    myArray[i]=NULL;
    }

    delete [] myArray;
    myArray=NULL;

    Now I have tried this and it didn't work, although my 2D array is of type dataType* so it is in effect a 3D array and so I have an extra for() loop for that.

    ReplyDelete
  2. Thanx for asking

    First of all since myArray is a pointer to a pointer, you should allocate it like

    myArray=new dataType *[width];

    which means allocating an array of pointers.

    your deallocating part seems correct to me, YOU DON'T NEED to use muArray=NULL though.

    ReplyDelete
  3. Scilly_guy4:50 AM

    This comment has been removed by a blog administrator.

    ReplyDelete
  4. You teach good!
    The language you use is quite simple.
    And I understand the dynamic memory allocation very well.

    ReplyDelete
  5. Hi maria,

    Thanks very much!
    Enjoy.

    ReplyDelete
  6. Anonymous8:53 AM

    Hi thanks.. but i what to know the dynamic memory allocation for two dimensional array... will u please help me.....

    ReplyDelete
  7. Hi

    You cannot directly allocate multi-dimensional arrays. I've seen a nice tutorial on how to do this:

    http://www.geocities.com/varunhostel/TechnicalArticles/PointerArticle/PointerArticle_Part2.html?reload_coolmenus#pos9

    ReplyDelete
  8. Anonymous12:21 AM

    Its really good man...

    ReplyDelete
  9. Hi Anonymous,

    Thanks! :-)

    ReplyDelete
  10. Anonymous7:06 AM

    can anyone explain about copy constructor in c++?

    ReplyDelete
  11. Anonymous8:17 PM

    Pretty good explanation

    ReplyDelete
  12. Anonymous8:38 AM

    great helped alot been trying to get a handle on how to understand this your great dude!

    ReplyDelete
  13. Anonymous12:51 AM

    i understand about dynamic memory allocation so i wanna to say you thank you very very much keep in touch

    ReplyDelete
  14. Anonymous12:52 AM

    very nice. i appreciate you.

    ReplyDelete
  15. Anonymous12:30 PM

    plz give me a code for adding two matrices using dynamic memory allocation

    ReplyDelete
  16. Anonymous12:07 PM

    thankyou verymuch...

    ReplyDelete
  17. Anonymous3:17 PM

    thanksssssssss

    ReplyDelete
  18. thank you so much it really helped me understand dynamic memory allocation =)

    ReplyDelete
  19. nice work :-) keep good work going

    ReplyDelete
  20. suguna11:06 PM

    Its very much useful. Thank You.
    I have one doubht.

    int *ptr, a=10;
    ptr=&a;
    cout<<*ptr;

    whether the above prg can be said as an example for dynamic memory allocation?

    ReplyDelete
  21. @sugna,

    That isn't dynamic memory allocation, you're just pointing a pointer to a statically allocated data.

    ReplyDelete

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.