Learning Center
Plans & pricing Sign in
Sign Out

Dynamic memory allocation in C language


									  Visual Programming

Dynamic Memory Management

    Shehzad Ashraf Ch.

           V.P./Dynamic Memory        1
       management/shahzad/Spring 10
• Arrays are fixed size
      e.g. int arr[20];//creates an array having 20 elements of type int
         //(reserves 40 bytes of memory for arr)
      Array is assigned the memory at compile time, so we can’t wait until
         run time to specify the size of array
      int arr[size]; // error array size must be a constant

• In many cases It can’t be known in advance how
  much memory is needed at compile time.
  – e.g. We want to store the string typed by user
     • in the above case we can define an array sized to hold the
        largest string we expect. what if we created an array of size
        1000 and string length entered by user is just 5. its simply the
        wastage of memory.

                           V.P./Dynamic Memory                               2
                       management/shahzad/Spring 10
       Dynamic Memory Allocation
• C++ provides an operator new for obtaining a variable-
  length block of memory
   – new takes memory from Operating system and returns the
     starting address (pointer) of obtained memory. The pointer
     returned by new is of the appropriate type.( i.e. the type of
     contents of reserved memory )

   e.g. cin>>size;//takes value of size from user
   int* p=new int[size];//Reserves memory for an array of size entered by user and
                        // stores starting address of reserved memory to p .
   – In above case the pointer returned by new is of type int.
   char* pstr=new char[100];//reserves 100 bytes of memory and returns the pointer of
                              //reserved memory to pstr. Here pointer returned by new is
                               //of type char.
   float* pf=new float;//reserves 4 bytes of memory and returns pointer of reserved
                       //memory to pf, pointer returned by new is of type float

                                V.P./Dynamic Memory                                    3
                            management/shahzad/Spring 10
    Dynamic Memory De-allocation
• The memory allocated by new can be de-allocated by delete
• To ensure efficient use of memory, C++ provides new operator with
  a matched corresponding delete operator, which returns memory to
  operating system.
  e.g. int* pI=new int;
        delete pI;// will delete the memory pointed by pI.
  in above case pI is not deleted the memory reserved be new whose
  address was stored in pI is deleted (returned back to operating
  In case of deleting arrays subscript operator is used before pointer
  e.g. char* ps=new char[50];
      delete []ps; // deletes the array(50 bytes) whose address was stored in ps

                                 V.P./Dynamic Memory                               4
                             management/shahzad/Spring 10
  Example-Dynamic Memory Allocation
int Size;
void main()                                                      0
{                                                   p            1
     cout<<"Enter array size";                                   2
     int* p=new int[Size];
     for( int i=0; i<Size; i++)
     for( i=0; i<Size; i++)
             cout<<"\t"<< p[i];
delete [ ]p; //will delete the array

    Out Put
    Enter Array size 8[Enter]
    0           1          2           3        4         5      6   7
                                      V.P./Dynamic Memory                5
                                  management/shahzad/Spring 10
    Example-Dynamic Memory Allocation
char* str;
int size;

int main( )

    cout<<"Enter the length of your name ";
    str=new char[size+1]; // reserves size+1 bytes of memory
    cout<<"Enter your name ";// prompt for input.
    cin.getline(str,size,'#'); // takes the string from user and puts a ‘\0’ Null character at
                               // end of string.
    cout<<" \nYour Name is "<<str; // displays all the characters until ‘\0’ encountered.
    delete [ ]str;// delete memory reserved by new.
    return 0;
}                                              Out Put
                                               Enter the length of your name 14[Enter]
                                               Enter your name Naeem Ahmed #[Enter]
                                               Your Name is Naeem Ahmed
                                     V.P./Dynamic Memory                                         6
                                 management/shahzad/Spring 10
                           Dry Run

           After str=new char[size+1]; str is assigned the address of
           the array created by new operator.

       N     a    e    e   m         A   h    m      e   d   \0
           After cin.getline(str,size+1,’#’). The new array is assigned
           the string entered by user


Null        After delete [ ]str. The memory occupied by array which was
            created using new returned to Operating system now str is
            pointing to null

                          V.P./Dynamic Memory                             7
                      management/shahzad/Spring 10
        Creating Structures using new
• Structures can also be created by
  using new operator.
                                                              pSt       10      x
struct mSt {int x;       float y;    };
void main( )                                                            95.51
{    mSt* pSt=new mSt; //reserves memory for an                                 y
     //unnamed instance of mSt and returns its
     //address to pSt
     pSt->x=10;//accessing member x of instance
     pSt->y=90.51;                                                  Unnamed
     cout<<"\n int is"<<pSt->x<<"\t float is "<<pSt->y;             instance created
     delete pSt;//deletes memory assigned to pSt
                                                                    by new

    out put
    int is 10               float is 90.51

   The members of unnamed instance created by new can be accessed by
   its pointer using operator -> pronounced as point to. The members can
   also be accessed by indirection as (*pSt).x;
                                        V.P./Dynamic Memory                         8
                                    management/shahzad/Spring 10
          Creating objects using new
•   Similar to structures new can also be used to create objects of a class.
•   the members( data & functions ) of object created by new can be
    accessed by point to -> operator or using indirection.
class myclass { private:        int data;
          public: void setdata(int d){data=d;}                          *pMyobj
          void show(){cout<<"\n data is "<<data;}
               };                                            pMyobj                data
    void main( )                                                                  setdata
    myclass* pMyobj=new myclass;
    pMyobj->setdata(20);// call setdata of unnamed object
    (*pMyobj).show(); // call show of unnamed object                  Unnamed object
    delete pMyobj;//delete memory                                     created by new
        data is 20
                                  V.P./Dynamic Memory                                  9
                              management/shahzad/Spring 10
       Link List- a chain of pointers
• A link list is a flexible storage system. In link list space of each data
  item is obtained as needed with new operator.
• Each item in a link list is connected or linked to the next data item
  using a pointer.


                    10            7             25           11          a Node


     In link list each data item/link/Node can be represented by an
     instance of struct or an object of class. while whole link list can be
     an object of a class
                               V.P./Dynamic Memory                                10
                           management/shahzad/Spring 10
 Link List- a chain of pointers (cont...)
• A node can be represented by following structure

   struct Node{    int data;     Node *Next; };// data part and a pointer to next Node.

• The whole link list can be represented by a class LinkList
  having two Node pointers First and current and two member
  functions AddNode() to set the value of data part of Node and
  Show() to display the data of all nodes, along with a
  destructor that will de-allocate the memory acquired by linklist.

  class LinkList   {Node       *First, *Current;
                               public: void AddNode(int d); void Show();

                                   V.P./Dynamic Memory                                11
                               management/shahzad/Spring 10
           Link List- Adding Nodes
                                                           First   Current
• At start first and current will point to NULL
                                                 NULL        NULL
• After adding First Node using new operator
  First and Current both will point to the start With out any node
  node                                           added

• After Adding start Node, First and Current     First         10
  pointers will be assigned the address of start
  node. For adding more new Nodes Current        Current

  pointer will be used and First will not        Adding First Node
  disturbed. So Current pointer will be used for
  adding new nodew
                                   First              10       7

                           V.P./Dynamic Memory                               12
                       management/shahzad/Spring 10
        Link List- Deleting Nodes
First is the pointer of start node we will start deleting first node then
second and so on, but before deleting each node we will store its
Next pointer in temporary pointer to delete the next one. So we need
two pointers a Temp and Cur. Temp will be one node ahead of Cur.

If Temp is pointing to First node Cur will have NULL. for deleting
First node Cur will be assigned its address and Temp will be
assigned the address of next node by using Next pointer of Current
node. We need a while loop to delete all the nodes. This loop will
delete all nodes & will execute until the next pointer of the node is
not NULL (i.e. Last Node).
Node* Temp=First, *Cur=NULL;
                                 cout<<" Deleting "<<Cur->data;
                                 delete Cur;

                            V.P./Dynamic Memory                        13
                        management/shahzad/Spring 10
                       Example –Link List
struct Node{           int data;    Node* Next; };

class LinkList
Node        *First, *Current;
public:     LinkList() {First=NULL;Current=NULL;}

           void AddNode(int d);
           void Show();

           ~LinkList() {           cout<<"\n";
                                   Node* Temp=First, *Cur=NULL;
                                               cout<<" Deleting "<<Cur->data;
                                               delete Cur;

                                       V.P./Dynamic Memory                      14
                                   management/shahzad/Spring 10
           Example –Link List (Cont..)
void LinkList::AddNode(int d)
{   if(First==NULL)   {         First=new Node;                void main( )
                                First->Next=NULL;              {
                                Current=First;                 LinkList myList;
    else             {          Node* Temp=new Node;           for (int i=1;i<5;i++)
           Temp->data=d;                                       myList.AddNode(i*10);
           Current->Next=Temp;                                 myList.Show();
           Current=Current->Next;                              }
void LinkList::Show()

    Node* Temp=First;                 Out put
    {                                 10        20        30          40
           Temp=Temp->Next;           Deleting 10 Deleting 20 Deleting 30 Deleting 40

                                    V.P./Dynamic Memory                                15
                                management/shahzad/Spring 10
                     Link List
• Link List can be implemented in a variety of
  ways. These can be
  – A Queue
  – A Stack
  – Circular Link List
  – Singly Link List
  – Doubly Link List
  – Sorted Link List
  All these types are not mutually exclusive
  Note:- All operations that can be performed on arrays
    can also be performed on link list.

                      V.P./Dynamic Memory                 16
                  management/shahzad/Spring 10

To top