A.1 Static Program Analysis

Some programming errors can be detected using static analysis tools that analyze the program's source code. If you invoke GCC with -Wall and -pedantic, the compiler issues warnings about risky or possibly erroneous programming constructions. By eliminating such constructions, you'll reduce the risk of program bugs, and you'll find it easier to compile your programs on different GNU/Linux variants and even on other operating systems.

Using various command options, you can cause GCC to issue warnings about many different types of questionable programming constructs. The -Wall option enables most of these checks. For example, the compiler will produce a warning about a comment that begins within another comment, about an incorrect return type specified for main, and about a non void function omitting a return statement. If you specify the -pedantic option, GCC emits warnings demanded by strict ANSI C and ISO C++ compliance. For example, use of the GNU asm extension causes a warning using this option. A few GNU extensions, such as using alternate keywords beginning with _ _ (two underscores), will not trigger warning messages. Although the GCC info pages deprecate use of this option, we recommend that you use it anyway and avoid most GNU language extensions because GCC extensions tend to change through time and frequently interact poorly with code optimization.

Listing A.1 (hello.c) Hello World Program
main () 
   printf ("Hello, world.\n"); 

Consider compiling the "Hello World" program shown in Listing A.1. Though GCC compiles the program without complaint, the source code does not obey ANSI C rules. If you enable warnings by compiling with the -Wall -pedantic, GCC reveals three questionable constructs.

% gcc -Wall -pedantic hello.c 
hello.c:2: warning: return type defaults to 'int' 
hello.c: In function 'main': 
hello.c:3: warning: implicit declaration of function 'printf' 
hello.c:4: warning: control reaches end of non-void function 

These warnings indicate that the following problems occurred:

·         The return type for main was not specified.

·         The function printf is implicitly declared because <stdio.h> is not included.

·         The function, implicitly declared to return an int, actually returns no value.

Analyzing a program's source code cannot find all programming mistakes and inefficiencies. In the next section, we present four tools to find mistakes in using dynamically allocated memory. In the subsequent section, we show how to analyze the program's execution time using the gprof profiler.