There are three typical kinds of memory allocations:
An array of bytes
A data structure
An object
The following sections describe how the Microsoft Foundation Class Library facilities perform each of these typical tasks for both heap allocation and frame allocation.
Allocation of an Array of Bytes
·To allocate an array of bytes on the frame:
Define the array as shown by the following code. The array is automatically deleted and its memory reclaimed when the array variable exits its scope.
{
const int BUFF_SIZE = 128;
// allocate on the frame
char myCharArray[BUFF_SIZE];
int myIntArray[BUFF_SIZE];
// reclaimed when exiting scope
}
·To allocate an array of bytes (or any primitive data type) on the heap:
Use the new operator with the following array syntax:
const int BUFF_SIZE = 128;
// allocate on the heap
char* myCharArray = new char[BUFF_SIZE];
int* myIntArray = new int[BUFF_SIZE];
·To deallocate the arrays from the heap:
Use the delete operator as follows:
delete [] myCharArray;
delete [] myIntArray;
Allocation of a Data Structure
·To allocate a data structure on the frame:
Define the structure variable as follows:
struct MyStructType {...};
void SomeFunc(void)
{
// frame allocation
MyStructType myStruct;
// use the struct
myStruct.topScore = 297;
// reclaimed when exiting scope
}
The memory occupied by the structure is reclaimed when it exits its scope.
·To allocate data structures on the heap:
Use new to allocate data structures on the heap and deallocate them with delete as shown by the following examples:
// heap allocation
MyStructType* myStruct = new MyStructType;
// use the struct through the pointer ...
myStruct->topScore = 297;
delete myStruct;
·To allocate an object on the frame:
Declare the object as follows:
{
CPerson myPerson; // automatic constructor call here
myPerson.SomeMemberFunction(); // use the object
}
The destructor for the object is automatically invoked when the object exits its scope.
·To allocate an object on the heap:
Use the new operator, which returns a pointer to the object, to allocate objects on the heap. Use the delete operator to delete them.
// automatic constructor call here
CPerson* myPerson = new CPerson;
myPerson->SomeMemberFunction(); // use the object
delete myPerson; // destructor invoked during delete
Both the heap and the frame examples assumed that the CPerson constructor takes no arguments. Assume that the argument for the CPerson constructor is a pointer to char.
The statement for frame allocation is:
CPerson myPerson( "Joe Smith" );
The statement for heap allocation is:
CPerson* MyPerson = new CPerson( "Joe Smith" );