Get the skills that get the hot IT projects—fast.
home account info subscribe login search FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
[an error occurred while processing this directive]
Previous Table of Contents Next


Technique

The technique required to allocate memory is quite easy. The tricky part is the upkeep of allocated memory. When I say upkeep, I mean you are responsible for the creation and deletion of allocated memory. The C++ language is very powerful and offers you a lot of leverage, but you are also accountable for your actions. Keep this in mind when dealing with memory allocation.

The following source code demonstrates how to allocate and deallocate memory for various data types. The source also includes an example of dynamically allocated and deallocated derived types, namely arrays.

Steps

1.  Create a new subdirectory named CREATE under your base source directory.
2.  Start up your editor and type in the following source code:
// create.cpp - program to demonstrate the
// allocating and deallocating of memory in C++
#include <iostream>
using namespace std ;

struct values {
    long value1 ;
    long value2 ;} ;
const int MAX_ELEMENTS = 20 ;

int main()
{
    int *intArray ;
    intArray = new int[ MAX_ELEMENTS ] ;
    int i = 0 ;

    for(i = 0; i < MAX_ELEMENTS; i++ )
        intArray[i] = i ;

    for(i = 0; i < MAX_ELEMENTS; i++ )
        cout << “intArray[i] = “ << intArray[i] << endl ;

    delete []  intArray ;

    values *sArray = new values[ MAX_ELEMENTS ] ;

    for(i = 0; i < MAX_ELEMENTS; i++ )
    {
        sArray[i].value1 = i ;
        sArray[i].value2 = i * 10 ;
    }
    for(i = 0; i < MAX_ELEMENTS; i++ )
    {
        cout << “sArray[i].value1 = “ << sArray[i].value1 ;
        cout << “, sArray[i].value2 = “ << sArray[i].value2 <<
         ⇒endl ;
    }
    delete [] sArray ;

    return( 0 ) ;
}
3.  Save your work in a file named CREATE.CPP and return to the command line.
4.  Run your compiler and linker on CREATE.CPP.
5.  The output, when run, should appear as in the following:
intArray[i] = 0
intArray[i] = 1
intArray[i] = 2
...
intArray[i] = 19
sArray[i].value1 = 0, sArray[i].value2 = 0
sArray[i].value1 = 1, sArray[i].value2 = 10
sArray[i].value1 = 2, sArray[i].value2 = 20
...
sArray[i].value1 = 19, sArray[i].value2 = 190

How It Works

Let’s examine the code to see what is happening. Remember, if your compiler gives you an error for either of these two lines

#include <iostream>
using namespace std ;

simply place block comments (//) in front of the second line (or delete it) and change the first line to read iostream.h.

Moving through the source file, the next item you see is the declaration of struct values. It contains two int variables, value1 and value2.

The next line of code declares MAX_ELEMENTS to be a constant int. This constant is used to declare the maximum number of elements to be allocated.

Look at the first two statements in function main:

int *intArray ;
intArray = new int[ MAX_ELEMENTS ] ;

The first statement declares intArray to be a pointer to int. The second statement is a new expression. In C++, the result of a new expression is a pointer to the allocated type. This is why intArray is declared as a pointer to int. The expression on the right side of the assignment operator states “Allocate a block of memory capable of holding MAX_ELEMENTS (20) ints.” The memory manager will attempt to locate a contiguous area of memory large enough to hold the 20 ints. If operator new() obtains the requested memory, it returns a pointer to int, otherwise the new expression throws an exception. You will examine exceptions in How-To 1.7.

In C++, a new expression (consisting of operator new()) is used to allocate memory from the free store (also referred to as the heap). The free store is an area of memory used for dynamically allocated objects. The free store expands and contracts as objects are allocated and deallocated.

There are three types of new expressions. One allocates a single object of some type, the second allocates an array of objects, and the third type is called placement new. The following example demonstrates all three different types of new expressions:

int *intArray1,  *intArray2,  *intPlaced ;
intArray1 = new int( 5 ) ;

intArray2 = new int[ MAX_ELEMENTS ] ;

intPlaced = new (memoryBlock) int ;

The first statement declares three pointers to int. The second statement allocates a single int and that int contains the value 5. The parenthesized initializer expression is optional. The initializer expression is used to initialize an allocated object to some known value.

The second statement is array allocation. The value within the brackets tells operator new() how many objects to allocate. You cannot use the initializer expression when allocating arrays. (The exception to this rule is when allocating user-defined objects.)

The last statement allocates a single int; this int is placed in an area of memory specified within the parentheses after the keyword new. Memory is not actually allocated with placement new, but a pointer to the object is returned. The memory block must be a static memory block or allocated with a new expression. It is your responsibility to ensure that the memory block is properly deallocated.

The next two lines of code consist of a for loop and its statement. The loop is used to assign a value to each individual int allocated.

The next two lines consist of a second for loop that prints out the value of each individual int, thus verifying the contents of each.

The next line of code

delete []  intArray ;

is the delete expression. This particular form is the array delete expression; it is identified by the bracket [] notation. This form is used to deallocate an array of objects. To deallocate a single object, use operator delete without the bracket notation.

The next statement

values *sArray = new values[ MAX_ELEMENTS ] ;

allocates MAX_ELEMENTS (20) of type struct values. The for loop that follows initializes each member of each allocated struct to a known value. The subsequent for loop then prints out the value of each member of each allocated struct.

The statement that follows:

delete [] sArray ;

deallocates the array of structs sArray. The last line in the main function ends the program.


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.