Dynamic Memory Allocation

    reading: Dietel section 5.9, 7.6

Variably Sized Class Members

A "Smart Array" Class

class Array
{
    public:
                Array ( unsigned size ); // constructor  

                ~
Array ( ); // destructor

                int getData ( unsigned index );  // accessor
                void setData ( unsigned index, int value ); // mutator

    private:
                int array_size;
                int* data_elements;

};
  • Now we can declare variably-sized arrays in our functions
  • Array A( x );  // as long as x has unsigned int type
  • Array B(100);

We have to allocate sufficient memory in the constructor:

Array :: Array ( unsigned size )
{
    array_size = size;   

   data_elements = ( size > 0 ) ? new int [ array_size ] : 0; 

                                                       // new with length 0 does allocate wasted memory
                                                        // use
0 instead of NULL (defined as void* )

   for ( int i = 0; i < array_size; i++ )
        data_elements [ i ] = -1;          // could modify or omit initialization, as appropriate
};

Variations of new

  • Given: class A { public: A ( ); A ( int, char ); };  // two constructors
  • A* ptr1 = new A;              // memory for one A; default constructor called
  • A* ptr2 = new A ( );         // same as above; explicitly call default constructor
  • A* ptr3 = new A (8, 'b');  // memory for one A; other constructor used
  • A* ptr4 = new A [ 50 ];   // memory for 50 A's; only default constructor possible

Freeing Dynamically-Allocated Memory

  • Should delete all memory which was allocated with new
  • From above:
            delete ptr1; delete ptr2; delete ptr3;  // can only delete one at a time
            delete [] ptr4;  // must delete [ ] anything allocated with new [ ] ; no size
  • Just as we allocated in the constructor above, we need to deallocate in destructor

Array :: ~Array ( )
{
    delete [ ] data_elements;    // size tracked automatically by memory allocator
}

Multidimensional Pointer Management

int x;

class C { ... };

C** ArrayOfPointers;

ArrayOfPointers = new C*  [ x ];

for ( int i=0; i < x; i++)

     ArrayOfPointers [ i ] = new C ( constructor arguments );

 

for ( int i=0; i < x; i++)

     delete ArrayOfPointers [ i ] ;  // each allocated with new

delete [ ] ArrayOfPointers;          // allocated with new [ ]