Expert C Programming

(Jeff_L) #1

It was originally thought that the // comment convention would not alter the meaning of any


syntactically correct C code. Sadly, this is not so


a //*


//*/ b


is a/b in C, but is a in C++. The C++ language allows the C notation for comments, too.


The Compiler Date Is Corrupted


The bug described in this section is a perfect example of how easy it is to write something in C that
happily compiles, but produces garbage at runtime. This can be done in any language (e.g., simply
divide by zero), but few languages offer quite so many fruitful and inadvertent opportunities as C.


Sun's Pascal compiler had been newly "internationalized," that is, adapted so that (among other things)
it would print out dates on source listings in the local format. Thus, in France the date might appear as


Lundi 6 Avril 1992. This was achieved by having the compiler first call stat() to obtain the


sourcefile modification time in UNIX format, then call localtime() to convert it to a struct tm,


and then finally call the strftime() string-from-time function to convert the struct tm time to an


ASCII string in local format.


Unhappily, there was a bug that showed up as a corrupted date string. The date was actually coming
out not as


Lundi 6 Avril 1992


but rather in a corrupted form, as


Lui*7& %' Y sxxdj @ ^F


The function only has four statements, and the arguments to the function calls are correct in all cases.
See if you can identify the cause of the string corruption.


/* Convert the source file timestamp into a localized date


string */


char *


localized_time(char * filename)


{


struct tm *tm_ptr;


struct stat stat_block;


char buffer[120];


/ get the sourcefile's timestamp in time_t format /


stat(filename, &stat_block);


/* convert UNIX time_t into a struct tm holding local time


*/


tm_ptr = localtime(&stat_block.st_mtime);

Free download pdf