17.7 Runtime Errors

I l @ ve RuBoard

Runtime errors are usually the easiest to fix. Following are some types of runtime errors:

Segmentation violation

This error indicates that the program tried to dereference a pointer containing a bad value.

Stack overflow

The program tried to use too many temporary variables . Sometimes this means the program is too big or using too many big temporary arrays, but most of the time this is due to infinite recursion problems. Almost all Unix systems automatically check for this error. Borland-C++ will check for stack overflow only if the compile-time option -N is used.

Divide by zero

Divide by zero is an obvious error. Unix masks the problem by reporting an integer divide by zero with the error message Floating exception ( core dumped).

In all cases, program execution will be stopped . In Unix, an image of the running program, called a core file, is written out. This file can be analyzed by the debugger to determine why the program died. Our first run of Example 17-4 resulted in a core dump. (One of the problems with core dumps is that the core files are very big and can fill up a disk quickly.)

One problem with runtime errors is that when they occur, program execution stops immediately. The buffers for buffered files are not flushed. This can lead to some unexpected surprises . Consider Example 17-5.

Example 17-5. debug/flush.cpp
 #include <iostream> int main(  ) {     int i,j;    /* two random integers */     i = 1;     j = 0;     std::cout << "Starting\n";     std::cout << "Before divide...";     i = i / j;  // divide by zero error      std::cout << "After\n";     return(0); } 

When run, this program outputs:

 Starting  Floating exception (core dumped) 

This might lead you to think the divide had never started, when in fact it had. What happened to the message "Before divide..."? The cout statement executed and put the message in a buffer; then the program died. The buffer never got a chance to be emptied.

By putting explicit flush-buffer commands inside the code, we get a truer picture of what is happening, as shown in Example 17-6.

Example 17-6. debug/flush2.cpp
 #include <iostream> int main(  ) {     int i,j;    /* two random integers */     i = 1;     j = 0;     std::cout << "Starting\n";     std::cout.flush(  );     std::cout << "Before divide...";     std::cout.flush(  );     i = i / j;  // divide by zero error      std::cout << "After\n";     std::cout.flush(  );     return(0); } 

The flush statement makes the I/O less efficient, but more current.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net