dynamic memory allocation

Discussion in 'C++' started by vamsi1990, Aug 26, 2008.

  1. vamsi1990

    vamsi1990 New Member

    Joined:
    Aug 26, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    i just want to know about dynamioc memopry allocation.i allocated the space using new operator for an entire array of 5 numbers of type int.
    i deallocated the space using delete keyword for the entire array.
    now my doubt is hw we can see that the memory hasbeen deallocated.if we think that the memory is deallocated in side the system implictly trhen when again i started printing the array the elements inside it again gettng printed.so after the space hasbeen deallocated hw the elements inside gets printed.if this is possible then we can save many bytes of space.
    if the memory hasbeen deallocated then from wher the elements geting printed.
    iam postng u the program related to my doubt


    Code:
    #include <iostream>
    using namespace std;
    
    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;
      }
      for (n=0; n<i; n++)
          cout << p[n] << ", ";
      return 0;
    }
    this is the program done by me wher i got the above doubts
     
  2. ranjittechie

    ranjittechie New Member

    Joined:
    Jul 8, 2008
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Hello ,
    If u saw carefullly after deleting P array only junk values were printed not the ones which are assigned to it. so it means that space got freed.

    i Hope this shall clear ur doubt

    regards
    ~ranjit
     
  3. hkp819

    hkp819 New Member

    Joined:
    Dec 4, 2008
    Messages:
    59
    Likes Received:
    1
    Trophy Points:
    0

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice