Portability gripe

David Mathog mathog at seqvax.caltech.edu
Fri Feb 10 13:43:00 EST 1995


In porting code from Unix to VMS I've more than once run into the following 
class of problem in otherwise clean C code. Specifically, the problem is 
the practice of overwriting string literals, either explicitly or implicitly.

This is NOT portable.  PLEASE cease and desist!  

Finding these errors can be a real pain, it always requires a trip into
debugger land, and that can be really time consuming.



Citing chapter and verse (kindly provided by Steve Lionel):
    ANSI Standard Section 3.1.4

      "If the program attempts to modify a string literal of either form,
       the behavior is undefined."



Here are some explicit cases, lifted from actual applications.  (They have
been slightly simplified to better illustrate the problem.)

Explicit modification of string literal:

    static char *bad = "ABCDEF";
/* some intervening code not affecting bad*/
    sprintf(bad,"BCDEFG");

This apparently runs on most Unixes, but generates an access violation on 
VMS when sprintf executes.  Both results are allowed by the standard, so
don't write code like this!!! 

Here is one of (many) ways to do it cleanly, just replace

    static char *bad = "ABCDEF";

               with

    static char bad[6] = "ABCDEF";


The implicit cases are even more of a pain to ferret out, but they
go something like this:

   /* somewhere in a program */
   somefunction(name,"string");
..

int somefunction(char *name, char *string);
    /* some code ...*/
    tolower(string);
    /* more code ...*/

This class of code runs ok on Unix, but gives an access violation on VMS.  
Again, both results are allowed by the ANSI C standard, so don't do this!!!

Since no compiler I'm familiar with can detect these errors at compilation
time it falls to the programmer to get the code right.

So get it right, ok?

Thanks,

David Mathog
mathog at seqvax.bio.caltech.edu
Manager, sequence analysis facility, biology division, Caltech 




More information about the Bio-soft mailing list