I l@ve RuBoard |
![]() ![]() |
Exercise 7.1The following function provides absolutely no checking of either possible bad data or the possible failure of an operation. Identify all the things that might possibly go wrong within the function (in this exercise, we don't yet worry about possible exceptions raised). int *alloc_and_init( string file_name ) { ifstream infile( file_name ); int elem_cnt; infile >> elem_cnt; int *pi = allocate_array( elem_cnt ); int elem; int index = 0; while ( infile >> elem ) pi[ index++ ] = elem; sort_array( pi, elem_cnt ); register_data( pi ); return pi; } The first error is a type violation: The ifstream constructor requires a const char* and not a string. To retrieve the C-style character string representation, we invoke the c_str() string member function: ifstream infile( file_name.c_str() ); Following the definition of infile, we should check that it opened successfully: if ( ! infile ) // open failed ... If infile did open successfully, the third statement executes but may not succeed. For example, if the file contained text, the attempt to place an element in elem_cnt fails. Alternatively, it is possible for the file to be empty. if ( ! infile ) // gosh, the read failed Whenever we deal with pointers, we must be concerned as to whether they actually address an object. If allocate_array() was unable actually to allocate the array, pi is initialized to 0. We must test that: if ( ! pi ) // geesh, allocate_array() didn't really The assumption of the program is that elem_cnt represents a count of the elements contained within the file. index is unlikely to overflow the array. However, we cannot guarantee that index is never greater than elem_cnt unless we check. |
I l@ve RuBoard |
![]() ![]() |