Home Segments Index Top Previous Next

644: Mainline

The following is one of the assignment statements in the current version of do_analysis:

train[car_count] = new engine (input_buffer); 

To prevent the memory leak, you use the delete operator before you reassign a pointer and lose your access to the memory you want to reclaim. You can, for example, deploy the delete operator just before the allocation of new objects:

...
delete train[car_count];  
switch (extract_car_code (input_buffer)) { 
  case eng_code: 
    train[car_count] = new engine (input_buffer); 
    break; 
  case box_code: 
    train[car_count] = new box_car (input_buffer); 
    break; 
  case tnk_code: 
    train[car_count] = new tank_car (input_buffer); 
    break; 
  case cab_code: 
    train[car_count] = new caboose (input_buffer); 
    break; 
} 
... 

So situated, the delete operator reclaims memory previously used by previously created class objects. Once reclaimed, memory automatically becomes available for subsequent applications of the new operator.

The first time that do_analysis is called, the train array contains pointers to 0, because the elements of global arrays are initialized to 0 by the C++ compiler. Fortunately, delete does nothing when its argument is 0.