Previous Section  < Free Open Study >  Next Section

Leak #3

Deleting an array of objects without using the square brackets on delete. A common point of confusion for C++ novices involves the use of the square brackets on the delete function; for example, delete[] p versus delete p. This size argument is unnecessary for deleting a single object, a single primitive data type (e.g., int, char, short), or an array of a primitive type. It is required for deleting arrays of any object that has a destructor defined on it. Variable-sized objects are a particularly vulnerable category of objects affected by this constraint. A variable-sized object is an object that contains a pointer to dynamically allocated space. (Note: For a more detailed discussion of variable-sized classes/objects and their ramifications, see "Towards a Minimal Public Interface for C++ Classes" and "A Framework for Variable-Sized Classes," The C++ Insider, Vol. 1, nos. 1 and 2, respectively.) The square brackets tell the compiler that the pointer is pointing to a vector of objects and that the destructor must be called along with the proper values for the object addresses (i.e., &array[0], &array[1], &array[2], etc.). If the brackets are not provided, then the pointer is assumed to be pointing at one object. The additional objects in the array will not have their destructors called, resulting in memory leakage. If a number is placed between the square brackets and is larger than the size of the array, then the compiler will call the destructor on invalid objects (memory overflow), resulting in heap corruption. If a number between square brackets is smaller than the size of the array, the compiler will not call the necessary number of constructors, resulting in memory leakage.

In all cases of memory leakage due to missing square brackets, the space taken up by the class (sizeof (class_name)) is put back on the heap because of the nature of new and delete. For this reason, some C++ developers claim the size argument is unnecessary for classes that do not have destructors defined on them. This is a dangerous coding convention since many such classes become variable-sized or have destructors added as the application matures. For example, a Point class containing two integer data members (x and y) might get a dynamically allocated string called color, (see Figure B.1), or a Meal class might add a melon pointer or even a melon object.

Figure B.1. Graphical representation of memory leak #3.


Some developers consider this memory leakage problem to be the worst because it cannot be eliminated by the class implementor since C++ is a multiparadigm language (i.e., it contains nonclass/object entities. In a pure system, an array class would handle the deletion correctly for all users. Of course, arrays could be made a C+ + class for a given application, eliminating this particular memory leakage problem.

    Previous Section  < Free Open Study >  Next Section