Dynamic Memory Allocation
reading: Dietel section 5.9, 7.6
Variably Sized Class Members
- Examples: character arrays for strings, lists of courses taken for a student, etc.
- Can sometimes request memory large enough to always be sufficient
- But want to be more memory-efficient; request only what's necessary
- Dynamic allocation: request an amount of memory determined at runtime
- Must make sure to free up requested memory after it's used
A "Smart Array" Class
class Array
{
public:
Array ( unsigned size ); // constructor
~Array ( ); // destructorint 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
- Array of pointers-to-type
- First allocate memory for pointers
- Then allocate memory to point to
- Similar to using malloc ( ) / calloc ( ) in C
- Generalize to more dimensions
int x;
class C { ... };
C** ArrayOfPointers;
ArrayOfPointers = new C* [ x ];
for ( int i=0; i < x; i++)
ArrayOfPointers [ i ] = new C ( constructor arguments );
- Must deallocate in reverse order of allocation
- Original array holds addresses of memory to be freed
- Generalize to more dimensions
for ( int i=0; i < x; i++)
delete ArrayOfPointers [ i ] ; // each allocated with new
delete [ ] ArrayOfPointers; // allocated with new [ ]