C Language

C's a Real Nowhere, Man

If you've ever watched Wile E. Coyote spinning his legs in thin air above some canyon floor, you've seen what happens when you try to use a C pointer that doesn't point to anything. C's macro name for this ticket to nowhere is NULL. It isn't hard to accidentally create null pointers; in fact, you get one every time you define a static pointer variable. Look at the following code:

 int val = 25;
 int *ptr;
 *ptr = val;

This code will be compiled but will either blow up or corrupt memory at runtime. Although ptr is defined as a pointer, it's value is initially NULL (or some undefined value). Thus, the assignment statement's target doesn't have a valid address. The two correct alternatives are:

 ptr = &val;

which assigns the address of val to ptr, or

 ptr  =
 (int *) malloc( sizeof( val ) );
 *ptr = val;

which (usually, as I explain in the next section) allocates memory to store the value 25. If you're counting on one of my "magic macros" to avoid this pitfall, you may be disappointed that I can offer only the shopworn C programming dictum: Be careful! Unless you're positive a pointer has been initialized, check it for NULL, as shown below, before using it:

 if ( ptr NE NULL ) {
    *ptr = val;
 }
 else {
    printf( "ptr is NULL\n");
 }

Some compilers let you generate checks for referencing uninitialized variables or NULL pointers, and you may want to use this defense both during development and for production applications.

by BrainBellupdated
Advertisement: